工厂模式

1. 工厂方法模式

Intent

  • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses(把对象的创建延迟到了子类来实现).
  • Defining a "virtual" constructor.
  • The new operator considered harmful.

Structure

工厂模式_第1张图片
Structure

实例Demo

  1. 类图


    工厂模式_第2张图片
    factory method by keith
  2. 代码:

public class Factory {
    public static void main(String[] args) {
        //test
        Pizza pizza;
        PizzaStore store = new NYPizzaStore();
        pizza=store.createPizza();
        pizza.print();

        store = new ChicagoPizzaStore();
        pizza=store.createPizza();
        pizza.print();
    }
}
//product
class Pizza {
    String store;

    public Pizza(String store) {
        this.store = store;
    }

    void print() {
        System.out.println("Pizza from " + store);
    }
}
abstract class PizzaStore {
    //factory method
    abstract Pizza createPizza();
}
class NYPizzaStore extends PizzaStore {

    @Override
    Pizza createPizza() {
        return new Pizza(getClass().getSimpleName());
    }
}
class ChicagoPizzaStore extends PizzaStore {

    @Override
    Pizza createPizza() {
        return new Pizza(getClass().getSimpleName());
    }
}
  1. Output
Pizza from NYPizzaStore
Pizza from ChicagoPizzaStore

2. 抽象工厂模式

Intent

  • Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  • A hierarchy that encapsulates: many possible "platforms", and the construction of a suite of "products".
  • The new operator considered harmful.

Structure

工厂模式_第3张图片
Structure

实例Demo

  1. 类图
工厂模式_第4张图片
abstract factory by keith
  1. 代码:
public class Factory {
    public static void main(String[] args) {
        //test
        PizzaStore store = new PizzaStore();
        store.makeOrder(1);
        store.makeOrder(2);
    }
}
//product
class Pizza {
    String factory;

    public Pizza(String store) {
        this.factory = store;
    }

    String description(){
        return "Pizza from "+factory;
    }
}
class PizzaStore {
    PizzaFactory factory;

    //factory method
    void makeOrder(int type) {
        if (type == 1) {
            factory = new PizzaFactory1();
        }
        if (type == 2) {
            factory = new PizzaFactory2();
        }
        Pizza pizza = factory.createPizza();
        System.out.println(pizza.description() + " is ready!");
    }
}
interface PizzaFactory {
    Pizza createPizza();
}
class PizzaFactory1 implements PizzaFactory {

    @Override
    public Pizza createPizza() {
        return new Pizza(getClass().getSimpleName());
    }
}
class PizzaFactory2 implements PizzaFactory {

    @Override
    public Pizza createPizza() {
        return new Pizza(getClass().getSimpleName());
    }
}
  1. Output
Pizza from PizzaFactory1 is ready!
Pizza from PizzaFactory2 is ready!

Refenrence

  1. Design Patterns
  2. 设计模式

你可能感兴趣的:(工厂模式)