工厂模式

概念:把产品创建过程的细节封装在工厂里的模式

优点:增加产品时抽象工厂不会改变,只要增加相应产品的实现工厂即可,提高了扩展性。

场景:适应单一系列产品的创建

简单工厂只是抽象工厂的一个特例:


fruit.properties文件:

apple = com.cn.test3.Apple
orange = com.cn.test3.Orange



Factory3类工厂文件:


interface Fruit {
    public void eat();
}
class Apple implements Fruit{
    public void eat() {
        System.out.println("吃苹果");
    }    
}
class Orange implements Fruit{
    public void eat() {
        System.out.println("吃橘子");
    }    
}
class Factory{
    public static Fruit getInstance(String className){
        Fruit fruit = null;
        try {
            /*
             * 采用Class.forName(className).newInstance()反射技术
             * */
            fruit = (Fruit)Class.forName(className).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return fruit;
    }
}
class Init{
    /*
     * 读取properties配置文件
     * */
    public static Properties getProperty(){
        Properties property = new Properties();
        File file = new File("E:\\myEclipseSpace\\testFactory\\bin\\com\\cn\\test3\\fruit.properties");
        try {
            if(file.exists()){
                property.load(new FileInputStream(file));
            }else{
                property.setProperty("apple", "com.cn.test3.Apple");
                property.setProperty("orange", "com.cn.test3.Orange");
                property.store(new FileOutputStream(file), "fruit class");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return property;
    }
}
public class Factory3{
    public static void main(String args[]){
        Properties property = Init.getProperty();
        Fruit f = Factory.getInstance(property.getProperty("apple"));
        if(f != null){
            f.eat();
        }
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值