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
factory method by keith
代码:
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());
}
}
- 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
abstract factory by keith
- 代码:
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());
}
}
- Output
Pizza from PizzaFactory1 is ready!
Pizza from PizzaFactory2 is ready!










网友评论