基本介绍:
工厂方法模式,又称工厂模式、多态工厂模式和虚拟构造器模式,通过定义工厂父类负责定义创建对象的公共接口,而子类则负责生成具体的对象。
作用:
将类的实例化(具体产品的创建)延迟到工厂类的子类(具体工厂)中完成,即由子类来决定应该实例化(创建)哪一个类。
解决的问题:
工厂一旦需要生产新产品就需要修改工厂类的方法逻辑,违背了“开放 - 关闭原则
package org.brando;
/**
*
* 类说明: 测试类
* @author Brando 2018年3月29日 下午2:03:59
*/
public class Launcher {
public static void main(String[] args) {
AAnimalFactory dogFactory = new DogFactory();
IAnimal dog = dogFactory.createAnimal();
dog.show();
AAnimalFactory catFactory = new CatFactory();
IAnimal cat = catFactory.createAnimal();
cat.show();
}
}
package org.brando;
/**
*
* 类说明: 动物接口
* @author Brando 2018年3月29日 下午3:07:36
*/
public interface IAnimal {
/**
*
* 方法说明: show自己.
* @author Brando 2018年3月29日 下午3:07:59
*/
public void show();
}
package org.brando;
/**
*
* 类说明: 猫
* @author Brando 2018年3月29日 下午3:09:14
*/
public class Cat implements IAnimal {
@Override
public void show() {
System.out.println("喵喵喵");
}
}
package org.brando;
/**
*
* 类说明: 狗
* @author Brando 2018年3月29日 下午3:08:43
*/
public class Dog implements IAnimal {
@Override
public void show() {
System.out.println("汪汪汪");
}
}
package org.brando;
/**
*
* 类说明: 抽象工厂
* @author Brando 2018年3月30日 下午2:14:13
*/
public abstract class AAnimalFactory {
/**
*
* 方法说明: 创建产品.
* @author Brando 2018年3月30日 下午2:14:23
* @return
*/
public abstract IAnimal createAnimal();
}
package org.brando;
/**
*
* 类说明: Cat工厂.
* @author Brando 2018年3月29日 下午3:10:15
*/
public class CatFactory extends AAnimalFactory {
@Override
public IAnimal createAnimal() { //创建Cat
return new Cat();
}
}
package org.brando;
/**
*
* 类说明: 动物工厂类.
* @author Brando 2018年3月29日 下午3:10:15
*/
public class DogFactory extends AAnimalFactory {
@Override
public IAnimal createAnimal() { //创建Dog
return new Dog();
}
}