工厂方法模式与普通工厂模式相比,没有违背“开放-封闭”原则。
利用反射,可以避免修改客户端代码。
/** * Created by hero on 16-4-2. */ public interface BaseFactory { void method(); } /** * Created by hero on 16-4-2. */ public class FactoryA implements BaseFactory { @Override public void method() { System.out.println("factory a"); } } /** * Created by hero on 16-4-2. */ public class FactoryB implements BaseFactory { @Override public void method() { System.out.println("factory b"); } } public class Main { public static void main(String[] args) { BaseFactory factory = new FactoryA(); factory.method(); } }
时间: 2024-10-26 08:32:18