工厂方法模式
当用户不知道要创建什么具体类的实例,或者不想在用户代码中指明要具体创建的实例时,我们可以使用工厂方法模式。
工厂方法模式是指定义一个用于创建对象的接口,然后利用实现类对方法进行实现,让实现的子类来决定具体实例化哪一个类。
工厂方法模式可以分三种:
1. 普通工厂模式
我们举一个例子进行说明:假设Animal接口有两个具体的实现类Dog和Cat。
我们在用户代码中并不想用Animal=new Dog()的方式创建实例,而是想尽可能的去隐藏掉我们的实现的具体类。我们可以定义一个Factory接口,让子类来决定具体实现哪一个类的实例化。
public interface Factory{
public Animal CreatAnimal(String type);
}
public class Factory1 implements Factory{
pubic Animal CreatAnimal(String type){
if(type.equals("Dog")){
return new Dog();
}else if(type.equals("Cat")){
return new Cat();
}else{
system.out.println("输入类型错误");
return null;
}
}
}
通过这用的方式,我们在客户代码中就可以只提供接口中的方法CreatAnimal来进行实例化,而不需要去暴露出具体的实现类。
我们通过Factory factory = new Factory1(); Animal A = factory.CreateAnimal(“Dog”);来实例化具体的类。
2. 多个工厂方法模式
多个工厂方法模式是对普通工厂模式的一个改进,不在需要客户输入参数,而是提供多个工厂方法来实例化对象。
public interface Factory{
public Animal CreatDog();
public Animal CreatCat();
}
public class Factory2 implements Factory{
pubic Animal CreatDog(){
return new Dog();
}
pubic Animal CreatCat(){
return new Cat();
}
}
3. 静态工厂方法模式
将工厂方法模式中的方法用static进行修饰,不需要创建工厂类的实例便可进行调用。
public class Factory3{
pubic static Animal CreatDog(){
return new Dog();
}
pubic static Animal CreatCat(){
return new Cat();
}
}
这样我们就可以直接利用Factory3.CreatDog()来实例化一个具体类了。