public class App { public static void main(String[] args) { createKingdom(new ElfKingdomFactory()); createKingdom(new OrcKingdomFactory()); } public static void createKingdom(KingdomFactory factory) { King king = factory.createKing(); Castle castle = factory.createCastle(); Army army = factory.createArmy(); System.out.println("The kingdom was created."); System.out.println(king); System.out.println(castle); System.out.println(army); } }
public interface King { } public interface Castle { } public interface Army { } public interface Army { }
<pre name="code" class="java">public interface KingdomFactory { Castle createCastle(); King createKing(); Army createArmy(); }
public class ElfKingdomFactory implements KingdomFactory { public Castle createCastle() { return new ElfCastle(); } public King createKing() { return new ElfKing(); } public Army createArmy() { return new ElfArmy(); } }
public class OrcKingdomFactory implements KingdomFactory { public Castle createCastle() { return new OrcCastle(); } public King createKing() { return new OrcKing(); } public Army createArmy() { return new OrcArmy(); } }
public class ElfArmy implements Army { @Override public String toString() { return "This is the Elven Army!"; } }
public class ElfKing implements King { @Override public String toString() { return "This is the Elven king!"; } }
public class ElfCastle implements Castle { @Override public String toString() { return "This is the Elven castle!"; } }
public class OrcArmy implements Army { @Override public String toString() { return "This is the Orcish Army!"; } }
public class OrcCastle implements Castle { @Override public String toString() { return "This is the Orcish castle!"; } }
public class OrcKing implements King { @Override public String toString() { return "This is the Orc king!"; } }
The kingdom was created. This is the Elven king! This is the Elven castle! This is the Elven Army! The kingdom was created. This is the Orc king! This is the Orcish castle! This is the Orcish Army!
Java设计模式-抽象工厂模式(Abstract Factory)
原文地址:http://blog.csdn.net/sinat_26227857/article/details/44453197