当前位置:网站首页>装饰器(二)
装饰器(二)
2020-11-08 21:03:00 【8Years】
//
// 模拟咖啡
// 1.抽象组件:需要装饰的抽象对象(接口或者抽象父类)
// 2.具体组件:需要装饰的对象
// 3.抽象装饰类:包含了对抽象组件的引用以及装饰着共有的方法
// 4.具体装饰类:被装饰的对象
public class TestDecoretorTwo {
public static void main(String[] args) {
Drink coffee = new coffee();
Drink suger = new Suger(coffee);
System.out.println(suger.cost() + "--->" + suger.Info());
Drink milk = new Milk(coffee);
System.out.println(milk.cost() + "--->" + milk.Info());
Drink milk1 = new Milk(suger);
System.out.println(milk1.cost() + "--->" + milk1.Info());
}
}
// 1.抽象组件
interface Drink{
int cost();
String Info();
}
// 2.具体组件:
class coffee implements Drink{
String name="原味咖啡";
public int cost() {
return 10;
}
@Override
public String Info() {
return name;
}
}
// 3.抽象装饰类:
class Decorate implements Drink{
//对抽象组件的引用
private Drink drink;
public Decorate(Drink drink) {
//这里是一个构造器(this)
this.drink = drink;
}
@Override
public int cost() {
return this.drink.cost();
}
@Override
public String Info() {
return this.drink.Info();
}
}
// 4.具体装饰类1:
class Milk extends Decorate{
public Milk(Drink drink) {
//这里是一个构造器,(super)
super(drink);
}
@Override
public int cost() {
return super.cost()*4;
}
@Override
public String Info() {
return super.Info()+"加入了牛奶";
}
}
// 4.具体装饰类2:
class Suger extends Decorate{
public Suger(Drink drink) {
super(drink);
}
@Override
public int cost() {
return super.cost()*2;
}
@Override
public String Info() {
return super.Info()+"加入了蔗糖";
}
}
输出结果
20--->原味咖啡加入了蔗糖
40--->原味咖啡加入了牛奶
80--->原味咖啡加入了蔗糖加入了牛奶
版权声明
本文为[8Years]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4583813/blog/4708229
边栏推荐
- Simple process of reading pictures by QT program developed by Python
- Dynamic relu: Microsoft's refreshing device may be the best relu improvement | ECCV 2020
- Exercise 5
- Summary of interface test case ideas
- 深拷贝
- The minimum insertion times of palindrome
- Constructors and prototypes
- 在Python中创建文字云或标签云
- Leetcode 45 jumping game II
- 进程 线程 协程
猜你喜欢
随机推荐
Introduction and application of swagger
【杂谈】JS相关的线程模型整理
Looking for a small immutable dictionary with better performance
IT industry salary has been far ahead! Ten years later, is the programmer still a high paying profession?
Iterm2 configuration and beautification
go语言参数传递到底是传值还是传引用?
git操作与分支管理规范
Swagger介绍和应用
C / C + + knowledge sharing: function pointer and pointer function, can you understand after reading this article?
Flink系列(0)——准备篇(流处理基础)
微信小程序相关
. net core cross platform resource monitoring library and dotnet tool
latex入门
Python 列表的11个重要操作
AI perfume is coming. Will you buy it?
动态规划设计:最大子数组
使用Fastai开发和部署图像分类器应用
RSA asymmetric encryption algorithm
experiment
Express framework