java 工厂模式和内部类的完美结合

java

package com.bikeqx.test;

public class Main{

public static void apply(ServiceFactory sf){

Service s = sf.getService();

s.method1();

s.method2();

}

public static void main(String[] args){

apply(A.servicefactory);

apply(B.servicefactory);

}

}

//顶层接口

interface Service{

void method1();

void method2();

}

//工厂接口

interface ServiceFactory{

Service getService();

}

class A implements Service{

@Override

public void method1() {

// TODO Auto-generated method stub

System.out.println("A method1");

}

@Override

public void method2() {

// TODO Auto-generated method stub

System.out.println("A method2");

}

//匿名内部类工厂

public static ServiceFactory servicefactory = new ServiceFactory(){

@Override

public Service getService() {

// TODO Auto-generated method stub

return new A();

}

};

}

class B implements Service {

@Override

public void method1() {

// TODO Auto-generated method stub

System.out.println("B method1");

}

@Override

public void method2() {

// TODO Auto-generated method stub

System.out.println("B method2");

}

public static ServiceFactory servicefactory = new ServiceFactory(){

@Override

public Service getService() {

// TODO Auto-generated method stub

return new B();

}

};

}

以上是 java 工厂模式和内部类的完美结合 的全部内容, 来源链接: utcz.com/z/389962.html

回到顶部