AOP之代理模式与装饰着模式

来源:互联网 发布:蜂窝数据qq打不开 编辑:程序博客网 时间:2024/05/21 17:45

AOP的实现是代理模式,但是装饰者模式也可以实现主要是装饰者模式jdk里没有支持实现aop

        装饰模式:增加程序的功能

        代理模式:给一个对象提供一个代理对象,并有代理对象来控制对原有对象的引用

AOP里面有几个关键词的解释:

1.关注点:我们进行关注公共功能

2.连接点:程序中需要增加功能的位置

3.advice:关注点的具体实现

4.方面:就是以上三点综合起来讲,在哪里增加什么功能并且具体怎么做

5.切入点:就是连接点的集合

6.目标对象就是那些:包含连接点的类




装饰者模式的例子:

package com.company;/** * Created by Dqd on 2017/4/16. */public abstract class Ope {    public abstract void op();}public class D1  extends Ope{    public void op(){        System.out.println("砖墙");    }}public class D2 extends Ope {    private Ope ope = null;    public D2(Ope ope1){        ope = ope1;    }    @Override    public void op() {        //有个被装饰的对象        System.out.println("正面腻子");        ope.op();        System.out.println("反面腻子");    }}public class Test {    public static void main(String[] args){        Ope ope = new D2(new D1());        ope.op();    }}




静态代理模式例子:

package proxy;/** * Created by Dqd on 2017/4/16. */public interface Api {    void t();}package proxy;/** * Created by Dqd on 2017/4/16. */public class Target implements Api{    @Override    public void t() {         System.out.println("我的目标");    }}package proxy;/** * Created by Dqd on 2017/4/16. *//** * 1.装饰模式的目的就是为程序增加功能 * 2.代理模式是代理对象访问,一般情况不为程序增加功能,但是也可以增加 * 3.当然了(静态代理)代理模式,如果代理的对象又好多的方法,那么需要在代理类中写好多方法,但是动态代理不需要 * */public class Proxy implements Api{    //需要有代理对象    private Api api;    public Proxy(Api api1){        api = api1;    }    @Override    public void t() {        //进行安全和日志的处理        /**         * if(安全){         *  继续进行         * }else{         *  不能正常进行         * }         */        System.out.println("代理ing-----安全检查");        if(true) {            api.t();        }else{        }    }}public class Test {    public static void main(String[] args){        Api api = new Proxy(new Target());        api.t();    }}


        这两种方式看上去十分的相似

0 0
原创粉丝点击