基本介绍:
简单工厂模式又称为静态工厂方法模式属于类的创建型模式
而它的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类的实例。 也就是生产你要创建的实体对象 。简单工厂模式实际上不属于23个GOF模式,但他可以作为工厂方法模式的一个引导.
示例代码:
package org.brando;
import org.brando.AnimalFactory.AnimalType;
/**
*
* 类说明: 测试类
* @author Brando 2018年3月29日 下午2:03:59
*/
public class Launcher {
public static void main(String[] args) {
IAnimal animal_1 = AnimalFactory.createAnimal(AnimalType.DOG);
animal_1.show();
IAnimal animal_2 = AnimalFactory.createAnimal(AnimalType.CAT);
animal_2.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:08:43
*/
public class Dog implements IAnimal {
@Override
public void show() {
System.out.println("汪汪汪");
}
}
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:10:15
*/
public class AnimalFactory {
/**
*
* 方法说明: 创建动物.
* @author Brando 2018年3月29日 下午3:12:40
* @param type 动物类型的枚举
* @return
*/
public static IAnimal createAnimal(AnimalType type) {
System.out.println("创建的动物是:" + type.name);
switch (type) {
case DOG:
return new Dog();
case CAT:
return new Cat();
default:
return null;
}
}
/**
*
* 枚举说明: 动物类型.
* @author Brando 2018年3月29日 下午3:11:56
*/
public enum AnimalType {
DOG("狗"), CAT("猫");
private String name;
AnimalType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}