• 简单工厂模式


    一、大致结构

    1、工厂类

    2、抽象产品类

    3、多个具体的产品类

    二、代码

    1、抽象产品类Fruit.java

    package com.simplefactory;
    
    public interface Fruit {
        
        public void grow();
        
        
    }

    2、具体子类Apple.java和Orangle.java

    package com.simplefactory;
    
    public class Apple implements Fruit {
    
        @Override
        public void grow() {
            System.out.println("我真在成长......");
    
        }
    
    }
    package com.simplefactory;
    
    public class Orangle implements Fruit {
    
        @Override
        public void grow() {
            System.out.println("grow......");
    
        }
    
    }

    3、将以上产品实现类放入配置文件

    fruitList.properties

    apple=com.simplefactory.Apple
    orangle=com.simplefactory.Orangle

    4、工具类

    FruitList.java

    package com.simplefactory;
    
    import java.io.IOException;
    import java.util.Properties;
    
    public class FruitList {
    
        private static Properties props;
        
        static {
            props = new Properties();
            try {
                //classpath加载文件需要/,如果你使用的是class Loader就不需要/
                //props.load(FruitList.class.getClassLoader().getResourceAsStream("fruitList.properties"));
                props.load(FruitList.class.getResourceAsStream("/fruitList.properties"));
            } catch (IOException e) {
                
                e.printStackTrace();
            }
            
        }
        
        public static String getProperty(String name) {
            
            return props.getProperty(name);
            
        }
        
    }

    5、静态工厂类

    SimpleFactory.java

    package com.simplefactory;
    
    public class SimpleFactory {
        
        public static Fruit createFruit(String name) {
            
            String className = FruitList.getProperty(name);
            
            Fruit fruit = null;
            
            try {
                fruit = (Fruit) Class.forName(className).newInstance();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            return fruit;
            
        }
        
    }

    6、测试类

    Test.java

    package com.simplefactory;
    
    public class Test {
        
        public static void main(String[] args) {
            Fruit apple = SimpleFactory.createFruit("apple");
            Fruit orangle = SimpleFactory.createFruit("orangle");
            
            apple.grow();
            orangle.grow();
        }
        
    }

    7、测试结果

  • 相关阅读:
    iOS Xcode制作模板类
    图片变形的抗锯齿处理方法
    iOS 9 分屏多任务:入门(中文版)
    iOS应用国际化教程(2014版)
    GitHub Top 100 简介
    iOS @synthesize var = _var 变量前置下划线解释
    @synthesize obj=_obj的意义详解 @property和@synthesize
    git 教程(14)--解决冲突
    git 教程(13)--创建与合并分支
    C++基础知识(3)---new 和 delete
  • 原文地址:https://www.cnblogs.com/honger/p/5958726.html
Copyright © 2020-2023  润新知