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();
		}
	};
}
posted @ 2016-10-16 17:55  浩大王  阅读(373)  评论(0编辑  收藏  举报