工厂模式有三个参与者,抽象产品(Product)、工厂(Creator)和具体产品(ConcreteProduct)。客户只会看到工厂和抽象产品。
public interface Product{
public String getName()
}
public class ConcreteProduct implements Product{
public String getName(){
return "产品1"
}
}
public class Creator{
public static Product create1(){
return new ConcreteProduct()
}
}
工厂模式的作用在于将创建具体产品的方法由工厂类控制,客户只需要知道产品的抽象类型
工厂模式就是在接口和子类之间加入了一个过渡端,通过此过渡端获得接口的实例化对象,这个过渡端也就是所谓的工厂类。这样以后如果再有程序子类要扩充,直接修改工厂类客户端就可以根据标记得到相应的实例,增加了程序的灵活性。eg:interface Fruit{
public void eat()
}
class Apple implements Fruit{
public void eat(){
System.out.println("** $$$$$")
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("** #####。")
}
}
class Factory{ // 定义工厂类
public static Fruit getInstance(String className){
Fruit f = null
if("apple".equals(className)){ // 判断
f = new Apple()
}
if("orange".equals(className)){ // 判断
f = new Orange()
}
return f
}
}
public class InterfaceCaseDemo{
public static void main(String args[]){
Fruit f = Factory.getInstance(null) // 实例化接口
f.eat()
}
}