面试题复习-常用设计模式-抽象工厂模式
抽象工厂与产品:
package com.ajax.pattern.abstractfactory; public interface FruitFactory { /** * 果肉 * @return */ Meat getMeat(); /** * 果皮 * @return */ Skin getSkin(); }
package com.ajax.pattern.abstractfactory; public abstract class Meat { abstract void desc(); }
package com.ajax.pattern.abstractfactory; public abstract class Skin { abstract void desc(); }
第一套产品:
package com.ajax.pattern.abstractfactory; public class AppleMeat extends Meat { @Override void desc() { System.out.println("苹果肉"); } }
package com.ajax.pattern.abstractfactory; public class AppleSkin extends Skin { @Override void desc() { System.out.println("苹果皮"); } }
第二套产品:
package com.ajax.pattern.abstractfactory; public class OrangeMeat extends Meat { @Override void desc() { System.out.println("橙肉"); } }
package com.ajax.pattern.abstractfactory; public class OrangeSkin extends Skin { @Override void desc() { System.out.println("橙皮"); } }
抽象工厂实现:
package com.ajax.pattern.abstractfactory; public class AppleFactory implements FruitFactory { @Override public Meat getMeat() { return new AppleMeat(); } @Override public Skin getSkin() { return new AppleSkin(); } }
package com.ajax.pattern.abstractfactory; public class OrangeFactory implements FruitFactory { @Override public Meat getMeat() { return new OrangeMeat(); } @Override public Skin getSkin() { return new OrangeSkin(); } }
运行:
package com.ajax.pattern.abstractfactory; public class Run { public static void main(String[] args) { FruitFactory f1 = new AppleFactory(); f1.getMeat().desc(); f1.getSkin().desc(); FruitFactory f2 = new OrangeFactory(); f2.getMeat().desc(); f2.getSkin().desc(); } }