设计模式研习手记:工厂方法模式(Factory Method)
在简单工厂模式中,原来在客户端要做的创建和初始化工作都移到了工厂里去做,虽然把对象的创建和初始化工作与客户端分离开了,但是所有对象创建和初始化的工作还是集中在了这个具体的工厂类里,如果要创建的对象很多,这个工厂类将会非常庞大,仍然不利于后期的代码维护。
?
工厂方法模式相对于简单工厂模式来说,就是把一个单一的工厂类,分成了多个具体的小工厂,并抽象出一个工厂类,这个工厂类只负责定义创建的方式,创建的具体内容由继承它的小工厂类来实现。
?
下面是一个利用工厂方法模式创建Tiger,Dolphin,Parrot的例子。
?
//****Animal.java package com.designpattern; public interface Animal { public void eat(); }
?
?
//****Tiger.java package com.designpattern; public class Tiger implements Animal { public void run() { System.out.println("Tiger is running!"); } public void eat() { System.out.println("Tiger is eating!"); } }
?
?
//****Dolphin.java package com.designpattern; public class Dolphin implements Animal { public void swim() { System.out.println("Dolphin is swimming!"); } public void eat() { System.out.println("Dolphin is eating!"); } }
?
?
//****Parrot.java package com.designpattern; public class Parrot implements Animal { public void fly() { System.out.println("Parrot is flying!"); } public void eat() { System.out.println("Parrot is eating!"); } }
?
//****Factory.javapackage com.designpattern;public interface Factory {public Animal createAnimal();}
?
//****TigerFactory.javapackage com.designpattern;public class TigerFactory implements Factory {public Animal createAnimal(){return new Tiger();}}
?
//****DolphinFactory.javapackage com.designpattern;public class DolphinFactory implements Factory {public Animal createAnimal(){return new Dolphin();}}
?
//****ParrotFactory.javapackage com.designpattern;public class ParrotFactory implements Factory {public Animal createAnimal(){return new Parrot();}}
?
//****Client.javapackage com.designpattern;public class Client {public static void main(String[] args){Factory factory = new TigerFactory();Animal animal = factory.createAnimal();animal.eat();factory = new DolphinFactory();Animal animal = factory.createAnimal();animal.eat();factory = new ParrotFactory();Animal animal = factory.createAnimal();animal.eat();}}
?
//****输出****Tiger is eating!Dolphin is eating!Parrot is eating!
?
总结:
工厂方法模式中,抽象工厂类负责定义创建对象的接口,具体对象的创建工作由实现抽象工厂的具体工厂类来完成。如果有新的产品加进来,只需要新增加一个具体的创建产品工厂类和具体的产品类就可以了。