TIJ......(三)

来源:互联网 发布:mac不安装flash 编辑:程序博客网 时间:2024/05/29 18:28

工厂方法:

package com.taray.factory;public interface Service {void method1();void method2();}

package com.taray.factory;public interface ServiceFactory {Service getService();}

package com.taray.factory;public class Implementation implements Service{public Implementation() {// TODO Auto-generated constructor stub}@Overridepublic void method1() {// TODO Auto-generated method stubSystem.out.println("implementsMethod1");}@Overridepublic void method2() {// TODO Auto-generated method stubSystem.out.println("implementsMethod2");}}
package com.taray.factory;public class ImplementsFacotry implements ServiceFactory {@Overridepublic Service getService() {// TODO Auto-generated method stubreturn new Implementation();}}

package com.taray.factory;public class Implementation2 implements Service{public Implementation2() {// TODO Auto-generated constructor stub}@Overridepublic void method1() {// TODO Auto-generated method stubSystem.out.println("implementation2 Mehtod1");}@Overridepublic void method2() {// TODO Auto-generated method stubSystem.out.println("implementation2 method2");}}

package com.taray.factory;public class ImplementsFactory2 implements ServiceFactory{@Overridepublic Service getService() {// TODO Auto-generated method stubreturn new Implementation2();}}
package com.taray.factory;/** * P187 * 接口是实现多重继承的途径,而生成遵循某个接口的对象的典型方式就是工厂方法设计模式, * 这和直接调用构造器不同,我们在工厂对象上调用的是创建方法,而该工厂对象将生成接口的某个 * 实现的对象。理论上,这种方式我们的代码将与接口完全的实现分离,这使得我们可以透明的 * 将某个实现替换为另一个实现。 * 如果不是用工厂设计方法,你的代码必须在某处指定将要创建的Service的确切类型,以便调用合适的构造器。 * @author Administrator * */public class Factories {public static void serviceConsumer(ServiceFactory factory){Service s=factory.getService();s.method1();s.method2();}public static void main(String[] args) {serviceConsumer(new ImplementsFacotry());serviceConsumer(new ImplementsFactory2());}}







0 0