为了账号安全,请及时绑定邮箱和手机立即绑定

设计模式--工厂模式--工厂方法模式

标签:
Java 设计
工厂模式有2种:工厂方法模式、抽象工厂模式
    *工厂方法模式:一个产品系列
    *抽象工厂模式:一个产品族(包含多个系列)

1.工厂方法模式的实现:以华为P8系列为例

 - 定义接口
    public interface HuaWeiP8SeriesInterface {
        public void draw();
    }

 - 实现接口
    public class P8Young implements HuaWeiP8SeriesInterface {
        @Override
        public void draw(){
            System.out.println("---------------P8青春版-------------");
        }
    }

    public class P8Standard implements HuaWeiP8SeriesInterface {
        @Override
        public void draw(){
            System.out.println("---------------P8标配版-------------");
        }
    }

 - 创建工厂
    public class P8_ProducteFactory() {
        public HuaWeiP8SeriesInterface getP8ByKey(String key) {
            Map<String, String> typeClassMap = new PropertiesUtils().getProperties();
            String classPath = typeClassMap.get(key);
            try{
                HuaWeiP8SeriesInterface p8 = Class.forName(classPath).newInstance();
                return p8;
            }catch (InstantiationException e) {
        e.printStackTrace();
        } catch (IllegalAccessException e) {
        e.printStackTrace();
        } catch (ClassNotFoundException e) {
        e.printStackTrace();
        }
            return null;
        }
    }

 - 测试类
public class Test {
    public static void main(String[] args) {
        P8_ProducteFactory factory = new P8_ProducteFactory();
        HuaWeiP8SeriesInterface p8 = factory.getP8ByKey("young");
        p8.draw();
    }
}

 - 测试结果
---------------P8青春版-------------


 * 为保证项目的可拓展性,利用properties配置文件,对产品的实体类进行配置

    例如:目前P8系列涉及两个产品:P8青春版、P8标配版
        编写P8Type.properties配置文件如下:
        young=com.factory.factory_method.P8Young
        standard=com.factory.factory_method.P8Standard

*为方便程序读取配置文件,创建PropertiesUtils工具类
    public class PropertiesUtils {
        public Map<String, String> getProperties() {
            Properties properties = new Properties();
            Map<String, String> map = new HashMap<String, String>();
            InputStream in = getClass().getResourceAsStream("P8Type.properties");
            try{
                properties.load(in);
                Enumeration en = properties.propertyNames();
                while(en.hasMoreElements()){
                    String key = (String)en.nextElement();
                    String property = properties.getProperty(key);
                    map.put(key, property);    
                }
            }catch(IOException e) {
                e.printStackTrace();
            }
            return map;
        }
    }

工厂模式的好处:利于项目的后期拓展。
若后期出现P8高配版,则只需在配置文件P8Type.properties中,配置P8高配版实体类的路径;客户端的“工厂”根据P8高配版的key值,调用getP8ByKey方法,即可获得新增的P8高配版实例

点击查看更多内容
4人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消