工厂方法模式

public interface Cake {
     void make();
}
public interface CakeFactory {
     Cake makeCake();
}
public class CreamCake implements Cake{
    /**
     * 鲜奶蛋糕
     */
    @Override
    public void make() {
        System.out.println("Making cream cake");
    }
}

public class FruitCake implements Cake {
    /**
     * 水果蛋糕
     */
    @Override
    public void make() {
        System.out.println("Making fruit cake");
    }
}
public class CreamCakeFactory implements CakeFactory{
    @Override
    public Cake makeCake() {
        System.out.println("Milking cows");
        return new CreamCake();
    }
}
public class FruitCakeFactory implements CakeFactory {

    @Override
    public Cake makeCake() {
        System.out.println("Picking fruit");
        return new FruitCake();
    }
}
public class Client {
    public static void main(String[] args) {
        CreamCakeFactory creamCakeFactory = new CreamCakeFactory();
        Cake cake1 = creamCakeFactory.makeCake();
        cake1.make();
        System.out.println("=================");
        FruitCakeFactory fruitCakeFactory = new FruitCakeFactory();
        Cake cake2 = fruitCakeFactory.makeCake();
        cake2.make();
    }
}

运行结果

Milking cows
Making cream cake
=================
Picking fruit
Making fruit cake

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