面试题复习-常用设计模式-工厂模式
产品接口:
package com.ajax.pattern.factorymethod; public interface Fruit { void desc(); }
产品1:
package com.ajax.pattern.factorymethod; public class Apple implements Fruit { @Override public void desc() { System.out.println("苹果"); } }
产品2:
package com.ajax.pattern.factorymethod; public class Orange implements Fruit { @Override public void desc() { System.out.println("橙子"); } }
工厂接口:
package com.ajax.pattern.factorymethod; public interface FruitFactory { Fruit getFruit(); }
产品1工厂:
package com.ajax.pattern.factorymethod; public class AppleFactory implements FruitFactory { @Override public Fruit getFruit() { return new Apple(); } }
产品2工厂:
package com.ajax.pattern.factorymethod; public class OrangeFactory implements FruitFactory { @Override public Fruit getFruit() { return new Orange(); } }
运行:
package com.ajax.pattern.factorymethod; public class Run { public static void main(String[] args) { Fruit fruit1 = new AppleFactory().getFruit(); fruit1.desc(); Fruit fruit2 = new OrangeFactory().getFruit(); fruit2.desc(); } }