简单工厂模式

一、大致结构

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、测试结果

原文地址:https://www.cnblogs.com/honger/p/5958726.html