设计模式---装饰模式

                                            装饰模式

概述

代码示例

原本继承的方式

public interface Car {
	
	public void show();
	
	public void run();
}
public class RunCar implements Car {

	public void run() {
		System.out.println("可以跑");
	}

	public void show() {
		this.run();
	}

}
public class SwimCar implements Car{

	public void run() {
		System.out.println("可以跑");
	}

	public void Swim() {
		System.out.println("可以游");
	}
	
	public void show() {
		this.run();
		this.Swim();
	}

}

主函数

public class MainClass {
	public static void main(String[] args) {
		Car flycar = new SwimCar();
		flycar.show();
	}
}

装饰模式的

 

public interface Car {
	
	public void show();
	
	public void run();
}

基本的对象

public class RunCar implements Car {

	public void run() {
		System.out.println("可以跑");
	}

	public void show() {
		this.run();
	}

}

因为相对其扩展所以进行装饰

public abstract class CarDecorator implements Car{
	private Car car;
	
	public Car getCar() {
		return car;
	}

	public void setCar(Car car) {
		this.car = car;
	}

	public CarDecorator(Car car) {
		this.car = car;
	}
	
	public abstract void show();
}
public class FlyCarDecorator extends CarDecorator{

	public FlyCarDecorator(Car car) {
		super(car);
	}

	public void show() {
		this.getCar().show();
		this.fly();
	}
	
	public void fly() {
		System.out.println("可以飞");
	}

	public void run() {
		
	}
}

 

public class SwimCarDecorator extends CarDecorator {

	public SwimCarDecorator(Car car) {
		super(car);
	}

	public void show() {
		this.getCar().show();
		this.swim();
	}
	
	public void swim() {
		System.out.println("可以游");
	}

	public void run() {
		
	}

}
public class MainClass {
	public static void main(String[] args) {
		Car car = new RunCar();
		
		car.show();
		System.out.println("---------");
		
		Car swimcar = new SwimCarDecorator(car);
		swimcar.show();
		System.out.println("---------");
		
		Car flySwimCar = new FlyCarDecorator(swimcar);
		flySwimCar.show();
	}
}

 实现三个功能

这里原本只能跑的车可以飞和游泳了,就是因为装饰了不同的东西。

抽象组件角色:Car

具体组件角色:RunCar

抽象装饰角色:CarDecorator

具体装饰角色:FlyCarDecorator

Io里面的缓冲流就用到了这个模式。缓冲流

全部评论

相关推荐

Java大菜狗:纯纯招黑奴,一天还不到两百那么多要求,还不迟到早退,以为啥啊,给一点工资做一堆活,还以不拖欠员工工资为荣,这是什么值得骄傲的事情吗,纯纯***公司
点赞 评论 收藏
分享
屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务