public interface Animal {
/**所有动物都会吃*/
public void eat();
}
public class Tiger implements Animal {
public void eat() {
System.out.println("老虎要吃饭!");
}
public void run() {
System.out.println("老虎要跑步!");
}
}
public class Parrot implements Animal {
public void eat() {
// TODO Auto-generated method stub
System.out.println("鹦鹉要吃饭");
}
public void fly() {
System.out.println("鹦鹉要飞翔");
}
public interface Factory {
/** 工厂类 */
public Animal createAnimal();
}
public class TigerFactory implements Factory {
public Animal createAnimal() {
// TODO Auto-generated method stub
return new Tiger();
}
}
public class DolphinFactory implements Factory {
public Animal createAnimal() {
// TODO Auto-generated method stub
return new Dolphin();
}
}
public class ParrotFactory implements Factory {
public Animal createAnimal() {
// TODO Auto-generated method stub
return new Parrot();
}
}
public class Client {
/**
* @param args
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Factory factory = new TigerFactory();
Animal animal = factory.createAnimal();
animal.eat();
factory = new DolphinFactory();
animal = factory.createAnimal();
animal.eat();
factory = new ParrotFactory();
animal = factory.createAnimal();
animal.eat();
}
}
定义:工厂方法模式中抽象工厂类负责定义创建对象接口,具体对象的创建工作由实现该抽象工厂的具体类实现;
原理:工厂方法模式由四部分组成:抽象工厂类,实现抽象工厂类的具体方法,抽象类,实现抽象类的具体方法;
优点:1、客户端不负责对象的创建,而把这个任务交给了具体的工厂类;2、新产品加进来,只需要新增一个具体的创建产品的工厂类;
缺点:使用该模式需要额外地编写代码,增加了工作量。
|