(二)工厂方法模式(FactoryMethod)
最后更新于:2022-04-01 15:48:07
工厂方法模式原理图:
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-07-12_578455cc845ca.png)
具体实现代码:
~~~
package com.designpattern.factorymethod;
public interface FactoryMethod {
public Animal createAnimal();
}
~~~
~~~
package com.designpattern.factorymethod;
public class DolphinFactory implements FactoryMethod {
@Override
public Animal createAnimal() {
return new Dolphin();
}
}
~~~
~~~
package com.designpattern.factorymethod;
public class TigerFactory implements FactoryMethod {
@Override
public Animal createAnimal() {
return new Tiger();
}
}
~~~
~~~
package com.designpattern.factorymethod;
public interface Animal {
public void eat();
}
~~~
~~~
package com.designpattern.factorymethod;
public class Dolphin implements Animal {
@Override
public void eat() {
System.out.println("Dolphin is eating");
}
public void swim() {
System.out.println("Dolphin is swimming");
}
}
~~~
~~~
package com.designpattern.factorymethod;
public class Tiger implements Animal {
@Override
public void eat() {
System.out.println("Tiger is eating");
}
public void run() {
System.out.println("Tiger is running");
}
}
~~~
~~~
package com.designpattern.factorymethod;
public class Client {
public static void main(String[] args) {
FactoryMethod factory = new TigerFactory();
Animal tiger = factory.createAnimal();
tiger.eat();
factory = new DolphinFactory();
Animal dolphin = factory.createAnimal();
dolphin.eat();
}
}
~~~
在工厂方法模式中,客户端不在负责对象的创建,而是把这个责任交给了具体的工厂类,客户端只负责对象的调用,从而明确各个类的职责。
如果有新的产品加进来,只需要新增加一个具体的创建产品的工厂类和具体的产品类就可以了,不会影响但原来的其他的代码,代码量也不会变大,后期维护更加容易,增强了系统的可扩展性。
但是使用这个模式的时候而外地编写代码,增加了工作量。