单例模式
1、配置文件读取类,协调系统整体行为
2、创建一个对象消耗资源过多
public class Singleton {
private static Singleton singleton = null;
//限制产生多个对象
private Singleton(){
}
//通过该方法获得实例对象
public static synchronized Singleton getSingleton(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
模板方法模式
工厂模式
代理模式
public Interface IUserDao{
public void eat();
}
public class UserDaoImpl implements IUserDao{
public void eat(){
//业务逻辑
}
}
public class UserDaoProxy implements IUserDao{
private IUserDao userDao;
public UserDaoProxy(IUserDao userDao){
this.userDao = userDao;
}
public void eat(){
//修饰
userDao.eat();
}
}
main(){
IUserDao userDao = new UserDaoProxy(new UserDaoImpl);
userDao.eat();
}
class MyHandler implements InvocationHandler{
private Object target;
public MyHandler(Object obj){
this.target = obj;
}
public Object invoke(Object proxy, Method method, Object[] args){
//加逻辑
Object result = method.invoke(target, args);
}
}
Interface IUserDao{
void eat();
}
class UserDaoImpl implements IUserDao{
void eat(){
//业务逻辑
}
}
main(){
IUserDao userDao = new UserDaoImpl();
MyHandler myHandler = new MyHandler(userDao);
IUserDao userDao = Proxy.newProxyInstance(classloader, userDao.getClass().getInterfaces(), myHandler);
userDao.eat();
}
网友评论