java设计模式之工厂模式
工厂模式
工厂模式概念
Class class=new Class();
如上代码通过new关键字实例化类Class的一个实例Class,但如果Class类在实例时需要一些初始化参数,而这些参数需要其他类的信息,则直接通过new关键字实例化时会增加代码的耦合度,不利于维护,因此需要通过工厂模式将创建实例和使用实例分开。将创建实例化的过程封装到工厂方法中,我们在使用时直接通过调用工厂方法来实现,不需要关心具体的实现过程。
实现
以创建手机为例,假设手机品牌有华为和苹果两种类型,我们要实现的是根据不同的传入参数实例化不同的手机。
UML图 :
- 定义接口
public interfac Phpone{ String brand(); }
- 定义实现类
public IPhone implements Phone{ public String brand(){ return "this is Apple phone"; } } public HuaWeiPhone implements Phone{ public String brand(){ return "this is a HuaWei Phone"; } }
- 定义工厂类
public class Factory{ public Phone createPhone(String phoneName){ if("HuaWei".equsal(phoneName)){ return new HuaWeiPhone(); }else if("Apple".equuals(phoneName)){ return new IPhone(); }else { return null; } } }
- 测试类
public class Test{ public static void main(String [] args){ Factory factory=new Factory(); Phone huawei=factory.createPhone("HuaWei"); Phone iphone=factory.createPhone("Apple"); System.out.println(huawei.brand()); Syetem.out.println(iphone.brand()); } }
- 结果