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

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

代理模式的关键在于代理类和被代理类需要实现同一个接口

代理模式实现的时候是不需要记住实现接口类的名称,仅仅需要记住接口的名称即可,通过不同的接口来实现不同的代理类。

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

    //正常的输出结果:
    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.
posted @ 2018-04-06 17:11  xingchen95  阅读(383)  评论(0编辑  收藏  举报