静态工厂方法只有一个工厂类,且如果要增加产品,则需要修改工厂类代码,违背了开闭原则。工厂方法模式则将工厂类颗粒化,为每一种产品单独设立一个工厂类。
package staticfactory; public interface Computer { public abstract void cal(); }
package net.mosang.factory; public class Mac implements Computer { @Override public void cal() { System.out.println("苹果电脑启动。。。。"); } }
package net.mosang.factory; public class HP implements Computer { @Override public void cal() { System.out.println("惠普电脑启动。。。。"); } }
package net.mosang.factory; public interface ComputerFactoryBasic { public abstract Computer CreateComputer(); }
package net.mosang.factory; public class MacFactory implements ComputerFactoryBasic { @Override public Computer CreateComputer() { return new Mac(); } }
package net.mosang.factory; public class HPFactory implements ComputerFactoryBasic { @Override public Computer CreateComputer() { return new HP(); } }
package net.mosang.factory; public class Client { public static void main(String[] args) { Computer computer = new MacFactory().CreateComputer(); Computer computer2 = new HPFactory().CreateComputer(); computer.cal(); computer2.cal(); } }
输出结果
苹果电脑启动。。。。 惠普电脑启动。。。。
>>