工厂方法模式(Factory Method):定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
package designMode.factoryMethod; interface IProduct { void function1(); void function2(); void function3(); }
package designMode.factoryMethod; class Product1 implements IProduct{ @Override public void function1() { System.out.println("我能实现功能1!"); } @Override public void function2() { System.out.println("我能实现功能2!"); } @Override public void function3() { System.out.println("我能实现功能3!"); } } class Product2 implements IProduct{ @Override public void function1() { System.out.println("我也能实现功能1!"); } @Override public void function2() { System.out.println("我也能实现功能2!"); } @Override public void function3() { System.out.println("我也能实现功能3!"); } }
package designMode.factoryMethod; interface IFactory { IProduct produce(); }
package designMode.factoryMethod; class Factory1 implements IFactory{ @Override public IProduct produce() { return new Product1(); } } class Factory2 implements IFactory{ @Override public IProduct produce() { return new Product1(); } }
package designMode.factoryMethod; class Test { public static void main(String[] args) { //创建产品1工厂 IFactory f1 = new Factory1(); // IFactory f2 = new Factory2(); IProduct p1 = f1.produce(); p1.function1(); p1.function2(); p1.function3(); } }
时间: 2024-10-10 15:56:06