工廠方法模式是簡單工廠模式進一步抽象和推廣。在工廠方法模式中,核心的工廠類再也不負責全部的產品的建立,而是將具體建立的工做交給子類去作。這個核心類則搖身一變,成爲抽象工廠的角色,僅負責給具體工廠子類必須實現的接口,而不接觸哪個產品類應當被實例化這種細節。java
1.工廠方法模式的結構ide
結構與角色code
package com.test; public interface Creator { /** * 工廠方法 * @return */ public Product factory(); }
package com.test; public interface Product { }
package com.test; public class ConcreteCreator1 implements Creator { /** * 工廠方法 */ @Override public Product factory() { return new ConcreteProduct1(); } }
package com.test; public class ConcreteProduct1 implements Product { public ConcreteProduct1() { super(); } }
package com.test; public class ConcreteProduct2 implements Product { public ConcreteProduct2() { super(); // TODO Auto-generated constructor stub } }
package com.test; public class ConcreteCreator2 implements Creator { /** * 工廠方法 */ @Override public Product factory() { return new ConcreteProduct2(); } }
package com.test; public class Client { private static Creator creator1,creator2; private static Product prod1,prod2; public static void main(String[] args) { creator1 = new ConcreteCreator1(); prod1 = creator1.factory(); creator2 = new ConcreteCreator2(); prod2 = creator2.factory(); } }