CS-Notes/notes/设计模式.md
2018-02-22 14:47:22 +08:00

40 KiB
Raw Blame History

?? 1 ?? ?????????

1. ?????????

?????????????????????????????????§Ö?????????????????û`?¨¢?

????????????????????????????????????????????????????

2. ????????

???????????????§Ó???????????§Ù????

3. ????????

??¨¹?§Ö?????????????????????????????????????????????????????§Ù????????????????????

4. ??????

????<3F>£??????<3F>£???????§Ü???§Ö?????????

?????????????????????? ?????????????????????????????????????????§Ö????????????????????????????????????????????????????????????????

????????????§Ü???§Ö???????????????????????§Ü???§Ö???????????????????§Ü???§Ù????

???????????¨¹?? ???????? has-a ????????????????????????????????????????Íè???????????????????¨À?????§à??????????§»??????????????????????????

???????????? Duck ??????? FlyBehavior ?? QuackBehavior ??performQuack() ?? performFly() ??????§Ú???????????????????????????? Duck ??????????????????? FlyBehavior ?? QuackBehavior ???????????????????????§Ú??

5. ????????

6. ??????

?????? ???????????ÈÉ???????????????????????????<3F>I????????????<3F>£?????????????????

7. ??????

public abstract class Duck {
    FlyBehavior flyBehavior;
    QuackBehavior quackBehavior;

    public Duck(){
    }

    public void performFly(){
        flyBehavior.fly();
    }

    public void setFlyBehavior(FlyBehavior fb){
        flyBehavior = fb;
    }

    public void performQuack(){
        quackBehavior.quack();
    }

    public void setQuackBehavior(QuackBehavior qb){
        quackBehavior = qb;
    }
}
public class MallarDuck extends Duck{
    public MallarDuck(){
        flyBehavior = new FlyWithWings();
        quackBehavior = new Quack();
    }
}
public interface FlyBehavior {
    void fly();
}
public class FlyNoWay implements FlyBehavior{
    @Override
    public void fly() {
        System.out.println("FlyBehavior.FlyNoWay");
    }
}
public class FlyWithWings implements FlyBehavior{
    @Override
    public void fly() {
        System.out.println("FlyBehavior.FlyWithWings");
    }
}
public interface QuackBehavior {
    void quack();
}
public class Quack implements QuackBehavior{
    @Override
    public void quack() {
        System.out.println("QuackBehavior.Quack");
    }
}
public class MuteQuack implements QuackBehavior{
    @Override
    public void quack() {
        System.out.println("QuackBehavior.MuteQuack");
    }
}
public class Squeak implements QuackBehavior{
    @Override
    public void quack() {
        System.out.println("QuackBehavior.Squeak");
    }
}
public class MiniDuckSimulator {
    public static void main(String[] args) {
        Duck mallarDuck = new MallarDuck();
        mallarDuck.performQuack();
        mallarDuck.performFly();
        mallarDuck.setFlyBehavior(new FlyNoWay());
        mallarDuck.performFly();
    }
}

??§ß??

QuackBehavior.Quack
FlyBehavior.FlyWithWings
FlyBehavior.FlyNoWay

?? 2 ?? ???????

1. ??????

???????????????????????????????????????????????????????????????????????????Subject??????????????????????????Observer???????????

2. ?????

?????§à??????????????????????????????????????????????????????§Ò????????§»???????

?????????????????????????????????????????????????§µ??????????????????????????????

3. ????????

???????????????????????????????????????????????§Ø???????????????????????

4. ??????????

5. ??????

????????????????????????? ????????????????????????????????????????????????????????????????????????ÒÔ????????????????????§Ö??????????<3F>£??

6. ??????

public interface Subject {
    public void resisterObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObserver();
}
import java.util.ArrayList;
import java.util.List;

public class WeatherData implements Subject {
    private List<Observer> observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData() {
        observers = new ArrayList<>();
    }

    @Override
    public void resisterObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        int i = observers.indexOf(o);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    @Override
    public void notifyObserver() {
        for (Observer o : observers) {
            o.update(temperature, humidity, pressure);
        }
    }

    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        notifyObserver();
    }
}
public interface Observer {
    public void update(float temp, float humidity, float pressure);
}
public class CurrentConditionsDisplay implements Observer {
    private Subject weatherData;

    public CurrentConditionsDisplay(Subject weatherData) {
        this.weatherData = weatherData;
        weatherData.resisterObserver(this);
    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        System.out.println("CurrentConditionsDisplay.update:" + temp + " " + humidity + " " + pressure);
    }
}
public class StatisticsDisplay implements Observer {
    private Subject weatherData;

    public StatisticsDisplay(Subject weatherData) {
        this.weatherData = weatherData;
        weatherData.resisterObserver(this);
    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        System.out.println("StatisticsDisplay.update:" + temp + " " + humidity + " " + pressure);
    }
}
public class WeatherStation {
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();
        CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData);
        StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);

        weatherData.setMeasurements(0, 0, 0);
        weatherData.setMeasurements(1, 1, 1);
    }
}

??§ß??

CurrentConditionsDisplay.update:0.0 0.0 0.0
StatisticsDisplay.update:0.0 0.0 0.0
CurrentConditionsDisplay.update:1.0 1.0 1.0
StatisticsDisplay.update:1.0 1.0 1.0

?? 3 ?? ?????

1. ????????

?????????????????????????????????????????????????????????????????????

2. ??????

?????????¦È??????????????????????????????????§Ú??§Ö?????????????

????? DarkRoast ???? Mocha ??????Mocha ??????? Whip ??????????????????????????????? cost() ????????????????? cost() ??????????????????? cost() ???????????????? DarkRoast ????? Mocha??????????? Mocha ???? DarkRoast?????????? Whip ?????? Whip ???? Mocha???????? cost() ?????????????????????????

3. ?????

??????????????????????????????§à?????????????????????????????????????????????????????????????????????????????????????????¦Í??¦²?????????????????????¦Å??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????¦Â?¦Å??????????§à??????????????????????§Ú??????????????

4. ???????????????

5. ??????

?????????????????????????????????????????????????????????§Ú??????????????????????????????????????????????????????????????????????????????????????????????????????????????§á??????????

6. Java I/O ?§Ö????????

7. ???????

public interface Beverage {
    public double cost();
}
public class HouseBlend implements Beverage{
    @Override
    public double cost() {
        return 1;
    }
}
public class DarkRoast implements Beverage{
    @Override
    public double cost() {
        return 1;
    }
}
public abstract class CondimentDecorator implements Beverage{
    protected Beverage beverage;
}
public class Mocha extends CondimentDecorator {

    public Mocha(Beverage beverage) {
        this.beverage = beverage;
    }

    @Override
    public double cost() {
        return 1 + beverage.cost();
    }
}
public class Milk extends CondimentDecorator {

    public Milk(Beverage beverage) {
        this.beverage = beverage;
    }

    @Override
    public double cost() {
        return 1 + beverage.cost();
    }
}
public class StartbuzzCoffee {
    public static void main(String[] args) {
        Beverage beverage = new HouseBlend();
        beverage = new Mocha(beverage);
        beverage = new Milk(beverage);
        System.out.println(beverage.cost());
    }
}

???

3.0

?? 4 ?? ??????

4.1 ?????

1. ????????

?§Ó???? Pizza??????????????¨°???????????????? Pizza ????

2. ????

?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????§µ??¨´????????????????????????????????????????????????????????????????????????????????§»????????????????????????????????§Ø???????????¨¹????????????§Ö????????????????????????????????????????????????????§Ö?????????????

3. ??????????

4. ???????

public interface Pizza {
    public void make();
}
public class CheesePizza implements Pizza{
    @Override
    public void make() {
        System.out.println("CheesePizza");
    }
}
public class GreekPizza implements Pizza{
    @Override
    public void make() {
        System.out.println("GreekPizza");
    }
}
public class SimplePizzaFactory {
    public Pizza createPizza(String type) {
        if (type.equals("cheese")) {
            return new CheesePizza();
        } else if (type.equals("greek")) {
            return new GreekPizza();
        } else {
            throw new UnsupportedOperationException();
        }
    }
}
public class PizzaStore {
    public static void main(String[] args) {
        SimplePizzaFactory simplePizzaFactory = new SimplePizzaFactory();
        Pizza pizza = simplePizzaFactory.createPizza("cheese");
        pizza.make();
    }
}

???§ß??

CheesePizza

4.2 ??????????

1. ????????

????????? Pizza ???????????????????????????¦Æ?????????????????íà?????????????? cheese ????? Pizza ?????????????????? Pizza ???????

2. ??????

?????????????????????????????????????????????????????????????????????????????

3. ?????

???????§µ???????????????????????????????§µ???????????????????????????????????????????????????????????????????????????????????????????§Õ????????????????????????????????????????????????????????????????????

4. ??????????

5. ???????

public interface Pizza {
    public void make();
}
public interface PizzaStore {
    public Pizza orderPizza(String item);
}
public class NYStyleCheesePizza implements Pizza{
    @Override
    public void make() {
        System.out.println("NYStyleCheesePizza is making..");
    }
}
public class NYStyleVeggiePizza implements Pizza {
    @Override
    public void make() {
        System.out.println("NYStyleVeggiePizza is making..");
    }
}
public class ChicagoStyleCheesePizza implements Pizza{
    @Override
    public void make() {
        System.out.println("ChicagoStyleCheesePizza is making..");
    }
}
public class ChicagoStyleVeggiePizza implements Pizza{
    @Override
    public void make() {
        System.out.println("ChicagoStyleVeggiePizza is making..");
    }
}
public class NYPizzaStore implements PizzaStore {
    @Override
    public Pizza orderPizza(String item) {
        Pizza pizza = null;
        if (item.equals("cheese")) {
            pizza = new NYStyleCheesePizza();
        } else if (item.equals("veggie")) {
            pizza = new NYStyleVeggiePizza();
        } else {
            throw new UnsupportedOperationException();
        }
        pizza.make();
        return pizza;
    }
}
public class ChicagoPizzaStore implements PizzaStore {
    @Override
    public Pizza orderPizza(String item) {
        Pizza pizza = null;
        if (item.equals("cheese")) {
            pizza = new ChicagoStyleCheesePizza();
        } else if (item.equals("veggie")) {
            pizza = new ChicagoStyleVeggiePizza();
        } else {
            throw new UnsupportedOperationException();
        }
        pizza.make();
        return pizza;
    }
}
public class PizzaTestDrive {
    public static void main(String[] args) {
        PizzaStore nyStore = new NYPizzaStore();
        nyStore.orderPizza("cheese");
        PizzaStore chicagoStore = new ChicagoPizzaStore();
        chicagoStore.orderPizza("cheese");
    }
}

???§ß??

NYStyleCheesePizza is making..
ChicagoStyleCheesePizza is making..

4.3 ???????

1. ??????

?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????íà????? PizzaStore ???????????????????????????? Pizza ?????????????????? Pizza ?????????????????¨´??? Pizza ????????????

2. ??????

???????????????????????????????ÈÉ???????????????????

3. ?????

????????????????????ÈÉ???????????????????????????§»??????????????????????????????????????????????????????????????????§Ü?????????????????????????????????????????????????AbstractFactory ?§Ö? CreateProductA ?? CreateProductB ????????????????????????????????????????????????????????????????????‰^?????????????????????????? Client ?????Client ???? AbstractFactory ????????????????????????????????????????????????§Ü?????????Client ??????????????§¿??????????????????????????????????????? Cilent ????? AbstractFactory ????????????????§³?

4. ??????????

5. ???????

public interface Dough {
    public String doughType();
}
public class ThickCrustDough implements Dough{

    @Override
    public String doughType() {
        return "ThickCrustDough";
    }
}
public class ThinCrustDough implements Dough {
    @Override
    public String doughType() {
        return "ThinCrustDough";
    }
}
public interface Sauce {
    public String sauceType();
}
public class MarinaraSauce implements Sauce {
    @Override
    public String sauceType() {
        return "MarinaraSauce";
    }
}
public class PlumTomatoSauce implements Sauce {
    @Override
    public String sauceType() {
        return "PlumTomatoSauce";
    }
}
public interface PizzaIngredientFactory {
    public Dough createDough();
    public Sauce createSauce();
}
public class NYPizzaIngredientFactory implements PizzaIngredientFactory{
    @Override
    public Dough createDough() {
        return new ThickCrustDough();
    }

    @Override
    public Sauce createSauce() {
        return new MarinaraSauce();
    }
}
public class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory{
    @Override
    public Dough createDough() {
        return new ThinCrustDough();
    }

    @Override
    public Sauce createSauce() {
        return new PlumTomatoSauce();
    }
}
public class NYPizzaStore {
    private PizzaIngredientFactory ingredientFactory;

    public NYPizzaStore() {
        ingredientFactory = new NYPizzaIngredientFactory();
    }

    public void makePizza() {
        Dough dough = ingredientFactory.createDough();
        Sauce sauce = ingredientFactory.createSauce();
        System.out.println(dough.doughType());
        System.out.println(sauce.sauceType());
    }
}
public class NYPizzaStoreTestDrive {
    public static void main(String[] args) {
        NYPizzaStore nyPizzaStore = new NYPizzaStore();
        nyPizzaStore.makePizza();
    }
}

???§ß??

ThickCrustDough
MarinaraSauce

?? 5 ?? ??????

1. ??????

???????????????????????????????????

2. ?????

???????? Java ??????????§Û????????????§à???????????????§à?????????¨²?????????§Ò????????????????¨²?????????????????¦·?????§à????????

3. ???????

????????§µ???§à???????????????????????????????????????????????????????????§à??????????????????????????????????????????????????????????????? if(uniqueInstance == null) ??????ï…????????????? uniqueInstance ??§à????????

public class Singleton {

    private static Singleton uniqueInstance;

    private Singleton() {
    }

    public static Singleton getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}

4. ???????????????????

?????? getUniqueInstance() ????????????????¡Â????????????????????????????? uniqueInstance ???????§Ø?????????????????????????????????????????????????????????????????

    public static synchronized Singleton getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }

5. ????????????????????

????????????????????????????

private static Singleton uniqueInstance = new Singleton();

6. ????????????????????

????????????????????????? getUniqueInstance() ???????§Þ?????????????????? uniqueInstance = new Singleton(); ?????????????¨À??????????????????§Ø? uniqueInstance ???????????????????????????????????

public class Singleton {

    private volatile static Singleton uniqueInstance;

    private Singleton() {
    }

    public static synchronized Singleton getUniqueInstance() {
        if (uniqueInstance == null) {
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

?? 6 ?? ??????

1. ????????

????????????????§Ü??????????????????????????????????????????????§Ù??????íà????????????³‡

2. ??????

??????????????????¨°????????????????????????

3. ?????

4. ??????????

Invoker ?????????????????????????????????????? execute() ??????Receiver ???????????????????????ConcreteCommand ?????????? Receiver ??????????????§Ú? Receiver ??????????????? LightOnCommand ????? excute ??????§Ú? Light ??????????Light ??????????? on() ??????????????Invoker ???? Client ??????????????????????? Invoker ?????????????????? Client ????????????§»??????

5. ???????

public interface Command {
    public void execute();
}
public class Light {

    public void on() {
        System.out.println("Light is on!");
    }

    public void off() {
        System.out.println("Light is off!");
    }
}
public class LightOnCommand implements Command{
    Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }
}
/**
 * ???????
 */
public class SimpleRemoteControl {
    Command slot;

    public SimpleRemoteControl() {

    }

    public void setCommand(Command command) {
        this.slot = command;
    }

    public void buttonWasPressed() {
        slot.execute();
    }

}
public class RemoteLoader {
    public static void main(String[] args) {
        SimpleRemoteControl remote = new SimpleRemoteControl();
        Light light = new Light();
        LightOnCommand lightOnCommand = new LightOnCommand(light);
        remote.setCommand(lightOnCommand);
        remote.buttonWasPressed();
    }
}

???

Light is on!

?? 7 ?? ???????????????

7.1 ????????

1. ??????

??????????????????????????????????????????????????????????????

2. ?????

??????????????????????????????????????????????????????????????????????Adapter??????????????????Adaptee???????????????????§Ú??????????????????????§µ?Adapter ??????? Target ?? Adaptee ?????????????? Adaptee ??????????????? Adapter ????????????? Target ?????????? Client ?????????????? Target ???????????

3. ????????

??????Duck????????Turkey????Duck ?? quack() ???????? Turkey ??? gobble() ?????????????? Turkey ??? Duck ?? quack() ??????

4. ??????????

5. ???????

public interface Duck {
    public void quack();
    public void fly();
}
public interface Turkey {
    public void gobble();
    public void fly();
}
public class WildTurkey implements Turkey{
    @Override
    public void gobble() {
        System.out.println("gobble!");
    }

    @Override
    public void fly() {
        System.out.println("fly!");
    }
}
public class TurkeyAdapter implements Duck{
    Turkey turkey;

    public TurkeyAdapter(Turkey turkey) {
        this.turkey = turkey;
    }

    @Override
    public void quack() {
        turkey.gobble();
    }

    @Override
    public void fly() {
        turkey.fly();
    }
}
public class DuckTestDrive {
    public static void main(String[] args) {
        Turkey turkey = new WildTurkey();
        Duck duck = new TurkeyAdapter(turkey);
        duck.quack();
        duck.fly();
    }
}

???§ß??

gobble!
fly!

7.2 ?????

1. ??????

???????????????????????????§Ö??????????????????????????????????????¨¢?

2. ?????

3. ????????

???????????????????????§Û???????????????????§Ó???????????§»????????¨¹???????????????????????????????????????????????????????

4. ??????????

5. ??????

?????????????????????????????????????????????????????????????????????

?? 8 ?? ??Ùã????

1. ??????

??????????§Ø??????????????????§»?????????????§³?

??Ùã????????????????????????????????????????§Ö??§»???ÒÂ

2. ?????

??Ùã?? templateMethod() ?????????????????? primitiveOperation1() ?? primitiveOperation2() ??????§Ö????? primitiveOperation1() ?? primitiveOperation2() ???????????????

3. ????????

?ÓÇ????õÂ?????????????????§»??????§Ö??????

4. ??????????

5. ??????

???????????????????´Â????????????????????´Â??????????????????????????????????????????????????????????????????????????????Ùã?????????????§Ú???????????????????????

6. ????

?????hock?????§»????????????§á??§á????????????????????????????????????????Ùã?? templteMethod() ?§µ??????????????????????????????????????

7. ???????

public abstract class CaffeineBeverage {

    final void prepareRecipe(){
        boilWater();
        brew();
        pourInCup();
        addCondiments();
    }

    abstract void brew();

    abstract void addCondiments();

    void boilWater(){
        System.out.println("boilWater");
    }

    void pourInCup(){
        System.out.println("pourInCup");
    }
}
public class Coffee extends CaffeineBeverage{
    @Override
    void brew() {
        System.out.println("Coffee.brew");
    }

    @Override
    void addCondiments() {
        System.out.println("Coffee.addCondiments");
    }
}
public class Tea extends CaffeineBeverage{
    @Override
    void brew() {
        System.out.println("Tea.brew");
    }

    @Override
    void addCondiments() {
        System.out.println("Tea.addCondiments");
    }
}
public class CaffeineBeverageTestDrive {
    public static void main(String[] args) {
        CaffeineBeverage caffeineBeverage = new Coffee();
        caffeineBeverage.prepareRecipe();
        System.out.println("-----------");
        caffeineBeverage = new Tea();
        caffeineBeverage.prepareRecipe();
    }
}

???§ß??

boilWater
Coffee.brew
pourInCup
Coffee.addCondiments
-----------
boilWater
Tea.brew
pourInCup
Tea.addCondiments

?? 9 ?? ?????????????

9.1 ????????

1. ??????

?????????????????????§Ö????????????????????????????????

2. ?????

?????????????????????????????????????????????????????????????????????????????????????????????????

3. ???????

public class Aggregate {

    private int[] items;

    public Aggregate() {
        items = new int[10];
        for (int i = 0; i < items.length; i++) {
            items[i] = i;
        }
    }

    public Iterator createIterator() {
        return new ConcreteIterator(items);
    }

}
public interface Iterator {
    boolean hasNext();
    int next();
}
public class ConcreteIterator implements Iterator {

    private int[] items;
    private int position = 0;

    public ConcreteIterator(int[] items) {
        this.items = items;
    }

    @Override
    public boolean hasNext() {
        return position < items.length;
    }

    @Override
    public int next() {
        return items[position++];
    }
}
public class Client {
    public static void main(String[] args) {
        Aggregate aggregate = new Aggregate();
        Iterator iterator = aggregate.createIterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

???§ß??

0
1
2
3
4
5
6
7
8
9

9.2 Java ??????????

1. ?????

Java ????????? Iterator ????????? Java ??????????????????? Iterable ????????????? iterator() ??????????? Iterator ??????? Java ??????????????????????????? foreach ????????????????§Ö????????

2. ???????

import java.util.Iterator;

public class Aggregate implements Iterable<Integer>{

    private int[] items;

    public Aggregate() {
        items = new int[10];
        for (int i = 0; i < items.length; i++) {
            items[i] = i;
        }
    }

    @Override
    public Iterator<Integer> iterator() {
        return new ConcreteIterator(items);
    }
}
import java.util.Iterator;

public class ConcreteIterator implements Iterator<Integer> {

    private int[] items;
    private int position = 0;

    public ConcreteIterator(int[] items) {
        this.items = items;
    }

    @Override
    public boolean hasNext() {
        return position < items.length;
    }

    @Override
    public Integer next() {
        return items[position++];
    }
}
public class Client {
    public static void main(String[] args) {
        Aggregate aggregate = new Aggregate();
        for (int item : aggregate) {
            System.out.println(item);
        }
    }
}

9.3 ?????

1. ??????

????????????????????????

2. ??????

???????????????¦Í???????????? / ???????¦Í???

??????????????????????????????????????

3. ?????

????????Composite???????????????Component???????????????¦Ë?????¦Í????§Þ???????????????????????????????????????????????

4. ???????

public abstract class Component {
    protected String name;

    public Component(String name) {
        this.name = name;
    }

    abstract public void addChild(Component component);

    public void print() {
        print(0);
    }

    abstract protected void print(int level);
}
public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void addChild(Component component) {
        throw new UnsupportedOperationException(); // ???????????????????? , ??????????????????????????
    }

    @Override
    protected void print(int level) {
        for (int i = 0; i < level; i++) {
            System.out.print("--");
        }
        System.out.println("left:" + name);
    }
}
import java.util.ArrayList;
import java.util.List;

public class Composite extends Component {

    private List<Component> childs;

    public Composite(String name) {
        super(name);
        childs = new ArrayList<>();
    }

    @Override
    public void addChild(Component component) {
        childs.add(component);
    }

    @Override
    protected void print(int level) {
        for (int i = 0; i < level; i++) {
            System.out.print("--");
        }
        System.out.println("Composite:" + name);
        for (Component component : childs) {
            component.print(level + 1);
        }
    }
}
public class Client {
    public static void main(String[] args) {
        Composite root = new Composite("root");
        Component node1 = new Leaf("1");
        Component node2 = new Composite("2");
        Component node3 = new Leaf("3");
        root.addChild(node1);
        root.addChild(node2);
        root.addChild(node3);
        Component node21 = new Leaf("21");
        Component node22 = new Composite("22");
        node2.addChild(node21);
        node2.addChild(node22);
        Component node221 = new Leaf("221");
        node22.addChild(node221);
        root.print();
    }
}

???§ß??

Composite:root
--left:1
--Composite:2
----left:21
----Composite:22
------left:221
--left:3

?? 10 ?? ????

1. ??????

?????????????????????????????????????????????????????

???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????íà????????????????????????????????????????????????§á???????????????????????§Ö???????????????????????????????????????????????????????????????????????

2. ?????

3. ????????

?????????§Ø????????????????????§Ó???????????????????????????????????????????

4. ?????????

???????????????????????—¨?§Ø??????????????????????§Ó????????????????????????????????????????§Ö???????????????????????????????????????????????

5. ???????????????

??????????????????—¨???????????????????§Ú???????????????????????????????????¦Í????????

6. ???????

public interface State {
    /**
     * ???25 ???
     */
    void insertQuarter();

    /**
     * ???25 ???
     */
    void ejectQuarter();

    /**
     * ???????
     */
    void turnCrank();

    /**
     * ???????
     */
    void dispense();
}
public class HasQuarterState implements State{
    private GumballMachine gumballMachine;

    public HasQuarterState(GumballMachine gumballMachine){
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("You can't insert another quarter");
    }

    @Override
    public void ejectQuarter() {
        System.out.println("Quarter returned");
        gumballMachine.setState(gumballMachine.getNoQuarterState());
    }

    @Override
    public void turnCrank() {
        System.out.println("You turned...");
        gumballMachine.setState(gumballMachine.getSoldState());
    }

    @Override
    public void dispense() {
        System.out.println("No gumball dispensed");
    }
}
public class NoQuarterState implements State {
    GumballMachine gumballMachine;

    public NoQuarterState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("You insert a quarter");
        gumballMachine.setState(gumballMachine.getHasQuarterState());
    }

    @Override
    public void ejectQuarter() {
        System.out.println("You haven't insert a quarter");
    }

    @Override
    public void turnCrank() {
        System.out.println("You turned, but there's no quarter");
    }

    @Override
    public void dispense() {
        System.out.println("You need to pay first");
    }
}
public class SoldOutState implements State {

    GumballMachine gumballMachine;

    public SoldOutState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("You can't insert a quarter, the machine is sold out");
    }

    @Override
    public void ejectQuarter() {
        System.out.println("You can't eject, you haven't inserted a quarter yet");
    }

    @Override
    public void turnCrank() {
        System.out.println("You turned, but there are no gumballs");
    }

    @Override
    public void dispense() {
        System.out.println("No gumball dispensed");
    }
}
public class SoldState implements State {
    GumballMachine gumballMachine;

    public SoldState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("Please wait, we're already giving you a gumball");
    }

    @Override
    public void ejectQuarter() {
        System.out.println("Sorry, you already turned the crank");
    }

    @Override
    public void turnCrank() {
        System.out.println("Turning twice doesn't get you another gumball!");
    }

    @Override
    public void dispense() {
        gumballMachine.releaseBall();
        if(gumballMachine.getCount()>0){
            gumballMachine.setState(gumballMachine.getNoQuarterState());
        } else{
            System.out.println("Oops, out of gumballs");
            gumballMachine.setState(gumballMachine.getSoldOutState());
        }
    }
}
public class GumballMachine {
    private State soldOutState;
    private State noQuarterState;
    private State hasQuarterState;
    private State soldState;

    private State state;
    private int count = 0;

    public GumballMachine(int numberGumballs) {
        count = numberGumballs;
        soldOutState = new SoldOutState(this);
        noQuarterState = new NoQuarterState(this);
        hasQuarterState = new HasQuarterState(this);
        soldState = new SoldState(this);

        if (numberGumballs > 0) {
            state = noQuarterState;
        } else {
            state = soldOutState;
        }
    }

    public void insertQuarter() {
        state.insertQuarter();
    }

    public void ejectQuarter() {
        state.ejectQuarter();
    }

    public void turnCrank() {
        state.turnCrank();
        state.dispense();
    }

    public void setState(State state) {
        this.state = state;
    }

    public void releaseBall() {
        System.out.println("A gumball comes rolling out the slot...");
        if (count != 0) {
            count -= 1;
        }
    }

    public State getSoldOutState() {
        return soldOutState;
    }

    public State getNoQuarterState() {
        return noQuarterState;
    }

    public State getHasQuarterState() {
        return hasQuarterState;
    }

    public State getSoldState() {
        return soldState;
    }

    public int getCount() {
        return count;
    }
}
public class GumballMachineTestDrive {
    public static void main(String[] args) {
        GumballMachine gumballMachine = new GumballMachine(5);

        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();

        gumballMachine.insertQuarter();
        gumballMachine.ejectQuarter();
        gumballMachine.turnCrank();

        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
        gumballMachine.ejectQuarter();

        gumballMachine.insertQuarter();
        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
    }
}

???§ß??

You insert a quarter
You turned...
A gumball comes rolling out the slot...
You insert a quarter
Quarter returned
You turned, but there's no quarter
You need to pay first
You insert a quarter
You turned...
A gumball comes rolling out the slot...
You insert a quarter
You turned...
A gumball comes rolling out the slot...
You haven't insert a quarter
You insert a quarter
You can't insert another quarter
You turned...
A gumball comes rolling out the slot...
You insert a quarter
You turned...
A gumball comes rolling out the slot...
Oops, out of gumballs
You can't insert a quarter, the machine is sold out
You turned, but there are no gumballs
No gumball dispensed

?? 11 ?? ?????? // TODO

?? 12 ?? ??????

12.1 MVC

12.1.1 ??? MVC

???????????????????????????????????????????????

12.1.2 Web ?§Ö? MVC

????????¨´????????

?? 13 ?? ?????????

???‰Ø??? ?? ??????? ???? ????? ?????????

?????????????????????????????????????????????????????????????????????????????????????

???????????????????????????????????????????ÖÎ??????§»?????????

??????

?? 14 ?? ?????? // TODO