publicclassiPhoneimplementsPhone { @Override publicvoidget() { System.out.println("Get the iPhone."); } }
再定义一个工厂类负责创建实例
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassPhoneFactory { publicstatic Phone producePhone(String brand)throws Exception { if (brand.equalsIgnoreCase("Huawei")) { System.out.println("A Huawei phone have been produced."); returnnewHuawei(); } elseif (brand.equalsIgnoreCase("iPhone")) { System.out.println("An iPhone have been produced."); returnnewiPhone(); } else { thrownewException("Sorry,the product of this brand can not be produced."); } } }
A Huawei phone have been produced. Get the Huawei phone.
若改为一个不存在的品牌,如boluo,则结果如下
1 2 3
java.lang.Exception: Sorry,the product of this brand can not be produced. at wyp.CreationalPatterns.SimpleFactoryPattern.Factory.PhoneFactory.producePhone(PhoneFactory.java:16) at wyp.CreationalPatterns.SimpleFactoryPattern.Client.main(Client.java:9)
publicclassiPhoneimplementsPhone { @Override publicvoidget() { System.out.println("Get the iPhone."); } }
定义抽象工厂类
1 2 3
publicinterfacePhoneFactory { public Phone producePhone(); }
定义与具体产品类对应的具体工厂类
1 2 3 4 5 6 7
publicclassHuaweiFactoryimplementsPhoneFactory { @Override public Phone producePhone() { System.out.println("A Huawei phone have been produced."); returnnewHuawei(); } }
1 2 3 4 5 6 7
publicclassiPhoneFactoryimplementsPhoneFactory { @Override public Phone producePhone() { System.out.println("An iPhone have been produced."); returnnewiPhone(); } }