1.模版方法模式:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中,模版方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤,还可以提供hook()让子类决定是否执行某些步骤。比如sort中的Comparable接口。
2.迭代器模式就是集合的迭代器
3.组合模式允许你将对象组合成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。比如树的遍历。
4.状态模式允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类
5.代理模式
(1)静态代理,很简单不说了
(2)动态代理,在运行时生成代理类,比如有一个Person类,当它使用自身代理时,只能修改name,而不能修改score。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Person{ //jdk代理必须有接口,因为它要继承Proxy类,而java不允许多继承
void setName(String name);
void setScore(String score);
String getName();
String getScore();
}
class PersonImpl implements Person{
private String name,score;
//get,set,toString
}
class OwnerInvocationHandler implements InvocationHandler{
private Person person; //处理器持有真实的对象
OwnerInvocationHandler(Person person){
this.person=person;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("setScore")){ //自己不能设置自己的分数
return null;
} else if (method.getName().startsWith("get")){
return method.invoke(person,args);
} else if (method.getName().startsWith("set")){
return method.invoke(person,args);
} else if (method.getName().startsWith("toString")){
return method.invoke(person,args);
}
return null;
}
}
public class Test {
static Person getOwnerProxy(Person person){
return (Person) Proxy.newProxyInstance( //使用Proxy类的静态方法
person.getClass().getClassLoader(), //将Person的类加载器当参数
person.getClass().getInterfaces(), //将Person的接口当参数
new OwnerInvocationHandler(person)); //调用处理器
}
public static void main(String[] args) {
Person person=new PersonImpl();
Person proxy=getOwnerProxy(person);
proxy.setName("张三"); //可以设置自己的名字
proxy.setScore("50"); //不能设置自己的分数
System.err.println(proxy); //Person{name='张三', score='null'}
}
}
原理,调用proxy.setScore("50"),
代理会掉用invoke(Object proxy,Method method,Object[] args)分别是代理类,方法,参数
然后return method.invoke(person,args),处理器持有真实的person对象