简单工厂模式

x33g5p2x  于2022-03-05 转载在 其他  
字(1.8k)|赞(0)|评价(0)|浏览(228)

1.概念

提供一个创建对象实例的功能,而无需关心其具体实现,被创建的实例的类型可以是接口,抽象类,也可以是具体的类。

2.简单案例(不灵活)

1.接口

package com.yl.design;

public interface Phone {
    void display();
}

2.实现类1

package com.yl.design;

public class Huawei implements Phone {
    @Override
    public void display() {
        System.out.println("Huawei...");
    }
}

3.实现类2

package com.yl.design;

public class Apple implements Phone {
    @Override
    public void display() {
        System.out.println("apple...");
    }
}

4.工厂类

package com.yl.design;

public class SimpleFactory {
    //私有化构造器,不给外部new
    private SimpleFactory(){}

    //定义一个静态的方法,用于生产对象
    public static Phone CreatePhone(int flag) {
        Phone phone = null;
        if (flag == 1) {
            phone = new Apple();
        } else if (flag == 2) {
            phone = new Huawei();
        }
        return phone;
    }
}

5.测试

package com.yl.design;

public class test {
    public static void main(String[] args) {
        Phone phone = SimpleFactory.CreatePhone(2);
        phone.display();
    }
}

3.可配置的简单工厂案例(灵活)

1.在原来代码的基础上,加多一个factory.properties文件

2.工厂(利用反射构造实例)

package com.yl.design;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Factory {
    private Factory(){}

    public static Phone createPhone() {
        Properties properties = new Properties();
        InputStream in = null;
        try {
            in = Factory.class.getResourceAsStream("factory.properties");
            properties.load(in);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //利用反射创建实例
        Phone phone = null;
        try {
            phone = (Phone)Class.forName(properties.getProperty("AppleClass")).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return phone;
    }
}

3.测试

package com.yl.design;

public class test {
    public static void main(String[] args) {
//        Phone phone = SimpleFactory.CreatePhone(2);
//        phone.display();
        Phone phone = Factory.createPhone();
        phone.display();
    }
}

相关文章