用内部类实现的工厂方法

从thinking in java 中摘过来的:
package com.cxz.j2se;   
  
interface  Service  {
	void method1();
	void methor2();
}
interface ServiceFactory{
	Service getService();
}
class Implemention1 implements Service{

	private Implemention1(){}
	@Override
	public void method1() {
		// TODO Auto-generated method stub
		System.out.println("method1");
		
	}

	@Override
	public void methor2() {
		// TODO Auto-generated method stub
		System.out.println("method2");
	}
	public static ServiceFactory factory  =  new ServiceFactory(){//工厂类,内部类,只调用一次
		public Service getService(){
			return new Implemention1();
		}
	};
}


public class MyClass {   
	public static void serviceConsumer(ServiceFactory fact) {
		Service s  =  fact.getService();
		s.method1();
		s.methor2();
	}
	public static void main(String args [] ){
		serviceConsumer(Implemention1.factory);//返回工厂类,然后可以调用工厂类的getService 方法类得到类的实例
	}
	
}  

你可能感兴趣的:(java,J2SE)