一、简单工厂
简单工厂通过传入的标识来生成对应的子类。
比如创建动物需要有动物父类,各个子类以及动物工厂。
public interface Animal{
public void create();
}
狗:
public class Dog implements Animal{
@Override
public void create(){
System.out.println("一条小狗");
}
}
鸟:
public class Bird implements Animal{
@Override
public void create(){
System.out.println("一只小鸟");
}
}
工厂类:
public class AnimalFactory{
public static Animal createAnimal(String type) throws Exception{
if (type.equalsIgnoreCase("小鸟")){
return new Bird ();
}else if (type.equalsIgnoreCase("小狗")){
return new Dog();
}else{
throw new Exception("对不起,暂时无法创造该动物。");
}
}
}
优点: 我们可以对创建的对象进行一些“加工”,且客户端无需知道其过程,拿来即用&