public interface Factory { public abstract Fruits product(); }
工厂接口
public interface Fruits { public abstract void growth(); }
水果接口
public class Apple implements Fruits { public Apple() { // TODO Auto-generated constructor stub } @Override public void growth() { System.out.println("买了个苹果"); } }
苹果类
public class Banana implements Fruits { public Banana() { // TODO Auto-generated constructor stub } @Override public void growth() { System.out.println("买了个香蕉"); } }
香蕉类
public class AppleFactory implements Factory { public AppleFactory() { // TODO Auto-generated constructor stub } @Override public Fruits product() { return new Apple(); } }
生产苹果工厂
public class BananaFactory implements Factory { public BananaFactory() { // TODO Auto-generated constructor stub } @Override public Fruits product() { return new Banana(); } }
生产香蕉工厂
public class Customer { public void buy(Factory factory){ Fruits fruit = factory.product(); fruit.growth(); } public static void main(String[] args) { Customer customer = new Customer(); customer.buy(new AppleFactory()); customer.buy(new BananaFactory()); } }
顾客类