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 工厂模式和内部类的完美结合
最新推荐文章于 2022-08-01 18:16:40 发布