a、静态工厂可以定义相关的名称,而构造器必须和类重名
b、不是每次调用都创建对象,可以根据需要自定义,可以创建实例缓存起来,避免重复创建对象
c、可以自定义返回值,可以是子类型的对象(服务提供者框架的基础)
d、简化代码、
服务提供者框架设计思想(JDBC,JMS设计)
设计如下:
场景:公司刷门禁卡进入
//对外提供服务的接口(接口A):
DoorInterface---------->门禁
package com.liangliang.coreJava.OPPTest;
/**
* 服务提供者框架设计思想
* @author sunliangliang
* 服务接口
*/
public interface DoorInterface {
public boolean in();
public boolean out();
}
//实现类:
public class DoorInterfaceImpl implements DoorInterface{
@Override
public boolean in() {
/** 业务逻辑验证*/
System.out.println("------------>in<-------------");
return false;
}
@Override
public boolean out() {
/** 业务逻辑验证*/
System.out.println("------------>out<-------------");
return false;
}
}
//对外提供服务接口(即接口A)的接口:
/**
* 接口服务提供者
* @author sunliangliang
*
*/
public interface DoorProviderInterface {
public DoorInterface getInterface();
}
//实现类:
public class DoorProviderInterfaceImpl implements DoorProviderInterface{
static{
DoorProviderManager.register("SOHU", new DoorProviderInterfaceImpl());
}
@Override
public DoorInterface getInterface() {
return new DoorInterfaceImpl();
}
}
//管理器
public class DoorProviderManager {
private DoorProviderManager(){}
private static final Map<String,DoorProviderInterface> providers=
new ConcurrentHashMap<String,DoorProviderInterface>();
public static void register(String name,DoorProviderInterface doorProvider){
providers.put(name, doorProvider);
}
public static DoorInterface getInstance(String name){
DoorProviderInterface doorProvider=providers.get(name);
return doorProvider.getInterface();
}
}
测试类
public class ClientTest {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.liangliang.coreJava.OPPTest.DoorProviderInterfaceImpl");
DoorInterface door=DoorProviderManager.getInstance("SOHU");
door.in();
door.out();
}
}