装饰模式;

//被装饰者
public class Car implements Person{
public void run(){
System.out.println(“速度20迈…”);
}
public void color(){
System.out.println(“彩虹滴颜色…”);
}
}

//装饰类
public class MyCar implements Person{
//装饰类中必须传入被装饰类的引用
public Car car;
public MyCar(Car car) {
this.car = car;
}
//在装饰类对run方法和color扩展,如果装饰类中对不需要扩展的方法调用被装饰类中的同名方法就ok了
@Override
public void run() throws InterruptedException {
car.run();
System.out.println(“我去4s车店加上了GTR的发动机…”);
System.out.println(“速度达到1000迈…”);
Thread.sleep(1000);
System.out.println(“还可以变形…”);
System.out.println(“真酷!!!嘻嘻…”);
}
@Override
public void color(){
car.color();
//System.out.println(“贴了彩虹车模显得更帅!!!”);
}
}

//装饰接口
public interface Person {
public void run() throws InterruptedException;
public void color();
}
//装饰模式\指的是在不改变原类,不使用继承的基础上,动态的扩展一个对象功能
//装饰类(我们定义的新类)和被装饰类(原类)必须实现相同的接口
public class Test {
public static void main(String[] args) {
//1.创建装饰者的对象
Car car = new Car();
//将被装饰者的对象传入构造
MyCar myCar = new MyCar(car);
//调用装饰者的方法:有一个异常try一下,不想try就往main上抛
try {
myCar.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
myCar.color();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值