码迷,mamicode.com
首页 > 编程语言 > 详细

Java的设计模式 之 简单的代理模式

时间:2018-04-06 18:35:52      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:ring   public   nts   rand   一段   输出   his   new   car   

下面是简单的代码外加一些个人的理解

此代码实现的目的:在已有的输出结果的之前和结束的位置上输出其他的信息。如下述的输出:

    //正常的输出结果:
    System.out.println("run ......");


    //要实现的样式:
    xxxxxxxxx;        //(其中xxxx表示的是为任意的输出)
    System.out.println("run .......");
    xxxxxxxxx;        //(其中xxxx同正常输出之前的输出)

要像实现上述的方法有两种办法:

方法一:(通过继承来输出上述的样式)

    //使用继承实现上述的要求
    //定义一个在LogProxy
    interface Moveable{
    public void move();
}


class Demo implements Moveable{
    public void move(){
        System.out.println("run........");
    }
}

class LogProxy extends Demo {
    public void move(){
        System.out.println("Car Log start ........");
        super.move();
        System.out.println("Car Log end ..........");
    }
}


class Test{
    public static void main(String[] args){
        LogProxy lp  = new LogProxy ();
        
        lp.move();
    }
}

使用上述代码的可以实现想要实现的结果,但是缺点是,想要嵌套多个类似的输出结果的话,需要在继承多个类,实现起来不方便。

方法二:(通过代理的方式来实现要求)

在写代码之前需要理解一个概念就是聚合:我通过查看资料和视频简单理解一下聚合的含义是在一个类中包含处除此类外的另一个类。

import java.util.Random;

interface Moveable{
    public void move();
}

class Tank implements Moveable{
    public void move(){
        System.out.println("run.....");
        
        try{
            Thread.sleep(new Random().nextInt(10000));                //此处的含义是将该线程停止一段时间
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

class TankTimeProxy implements Moveable{
    Moveable t;
    
    public TankTimeProxy(Moveable m){
        super();
        this. t = m;
    }
    
    public void move(){
        System.out.println("Time Proxy begin .....");
        t.move();
        System.out.println("Time Proxy end .......");
    }
}

class TankLogProxy implements Moveable{
    Moveable t ;
    
    public TankLogProxy(Moveable m){
        super();
        this.t = m;
    }
    
    public void move(){
        System.out.println("Log Proxy begin......");
        
        t.move();
        
        System.out.println("Log Proxy end .......");
    }
}

class Demo{
        public static void main(String[] args){
            Moveable m = new Tank();
        
        TankLogProxy tlp = new TankLogProxy(m);
        
        TankTimeProxy ttp = new TankTimeProxy(tlp);
        
        ttp.move();
    }
}

//使用代理实现开头的要求的一个条件是需要将所要使用到的类都需要实现一个统一的接口,上述代码中实现的接口是Moveable.

Java的设计模式 之 简单的代理模式

标签:ring   public   nts   rand   一段   输出   his   new   car   

原文地址:https://www.cnblogs.com/gxcstyle/p/8728146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!