您的位置:首页 > 其它

设计模式记录学习---后续

2016-03-30 16:18 225 查看
1、动态代理

了解java反射,获取类类三种方式Class.forName()、类名.class、类实例.getClass()

获取实例方法:无参2种、有参一种

类类.newInstance()

类类.getConstructor(Class[]{}).newInstance(Object[]{});

类类.getMethod(MethodName, Class[]{}).invoke(具体实例对象, Object[]{});

public class DynamicProxy implements InvocationHandler{
private Object targetObject;
public DynamicProxy(Object object)
{
this.targetObject=object;
}
public Object newProxyInstance(DynamicProxy dynamicProxy) {
return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
targetObject.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("before");
Object ret =method.invoke(targetObject, args);
if(args!=null){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
System.out.println("after");
return ret;
}
public static void main(String args[]){
DynamicProxy dynamicProxy=new DynamicProxy(new Vector());
List vector = (List)dynamicProxy.newProxyInstance(dynamicProxy);
vector.add("1");
vector.add(2);
System.out.println(vector);
}
}
2.装饰模式

抽象构件角色(Component):给出一个接口,以规范准备接收附加责任的对象

具体构件角色(ConcreteComponent):定义一个将要接收附加责任的类

装饰角色(Decorato):持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口

具体装饰角色(ConcreteDecoratoA、ConcreteDecoratoB):负责给构件对象“贴上”附加的责任

public interface Component {

public void doSomeThing();
}
public class ConcreteComponent implements Component {

@Override
public void doSomeThing() {
System.out.println("Component A");
}

}
public class Decorato implements Component {
private Component  component;

public Decorato(Component  component){

this.component=component;
}

@Override
public void doSomeThing() {
component.doSomeThing();
}

}


public class ConcreteDecoratoA extends Decorato {

public ConcreteDecoratoA(Component component) {
super(component);
}
@Override
public void doSomeThing() {
super.doSomeThing();
doOtherSomeThing();
}
public void doOtherSomeThing(){
System.out.println("Decorat----A");
}
}


public class ConcreteDecoratoB extends Decorato {

public ConcreteDecoratoB(Component component) {
super(component);
// TODO Auto-generated constructor stub
}

@Override
public void doSomeThing() {
super.doSomeThing();
doOtherSomeThing();
}
public void doOtherSomeThing(){
System.out.println("Decorat----B");
}

public static void main(String args[]) throws Exception{
Component component = new ConcreteDecoratoB(new ConcreteDecoratoA(new ConcreteComponent()));
component.doSomeThing();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: