个人见解甚浅,写博客纯是为了做笔记,希望大家不要被误导。
工厂模式:工厂方法模式:定义一个创建对象的接口(本例中是PizzaStore),但由子类决定要实例化的是哪个类。工厂方法让类把实例化推给子类(总之实例化不推给实体类,实现了实体类解耦)。
此例是pizza店订单系统。客户输入所要pizza种类,参数传进PizzaStore子类中,子类创建Pizza子类(比如NYCheesePizza)对象。
public class Pizza {
String name;
void prepare(){
System.out.print("Preparing" + name);
}
}
public class ChicagoStyleVeggiePizza extends Pizza {
public void ChicagoStyleVeggiePizza(){
name = "ChicagoStyleVeggiePizza";
}
}
public class NYStyleCheesePizza extends Pizza {
public NYStyleCheesePizza(){
name = "NYStyleCheesePizza";
}
}
public class NYStyleVeggiePizza extends Pizza{
public NYStyleVeggiePizza(){
name = "NYStyleVeggiePizza";
}
}
public abstract class PizzaStore {//里面定义了抽象的工厂方法,靠子类实现
public Pizza orderPizza(String style){
Pizza pizza = createPizza(style);
pizza.prepare();
return pizza;
}
public abstract Pizza createPizza(String style);
}
public class NYPizzaStore extends PizzaStore{//实现工厂方法
@Override
public Pizza createPizza(String style) {
Pizza pizza;
switch (style){
case "chesse": {
pizza = new NYStyleCheesePizza();
break;
}
case "veggie":{
pizza = new NYStyleVeggiePizza();
break;
}
default:pizza = null;//不加此句,会报pizza没有实例化的错
}
return pizza;
}
}
抽象工厂模式:提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
public interface AbstractFactoryPizza {
public IngredientThinCrustDough createIngredientThinCrustDough();
}
public class ThinCrustDoughFactory implements AbstractFactoryPizza {
@Override
public IngredientThinCrustDough createIngredientThinCrustDough() {
return new IngredientThinCrustDough();
}
}
public class PizzaIngredient {
public String name;
}
public class IngredientThinCrustDough extends PizzaIngredient{
public void IngredientThinCrustDough(){
name = "IngredientThinCrustDough";
}
}
public abstract class Pizza {
String name;
abstract void prepare();
}