当前位置:网站首页>Decorator (2)
Decorator (2)
2020-11-08 21:03:00 【8Years】
//
// Simulation coffee
// 1. Abstract components : Abstract objects that need decoration ( Interface or abstract parent class )
// 2. Specific components : Objects that need decoration
// 3. Abstract decorator : Contains references to abstract components and decorates common methods
// 4. Concrete decoration : Objects to be decorated
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. Abstract components
interface Drink{
int cost();
String Info();
}
// 2. Specific components :
class coffee implements Drink{
String name=" Original coffee ";
public int cost() {
return 10;
}
@Override
public String Info() {
return name;
}
}
// 3. Abstract decorator :
class Decorate implements Drink{
// References to abstract components
private Drink drink;
public Decorate(Drink drink) {
// Here's a constructor (this)
this.drink = drink;
}
@Override
public int cost() {
return this.drink.cost();
}
@Override
public String Info() {
return this.drink.Info();
}
}
// 4. Concrete decoration 1:
class Milk extends Decorate{
public Milk(Drink drink) {
// Here's a constructor ,(super)
super(drink);
}
@Override
public int cost() {
return super.cost()*4;
}
@Override
public String Info() {
return super.Info()+" With milk ";
}
}
// 4. Concrete decoration 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()+" Added sugar ";
}
}
Output results
20---> Original coffee with sugar
40---> Original coffee with milk
80---> Original coffee with sugar and milk
版权声明
本文为[8Years]所创,转载请带上原文链接,感谢
边栏推荐
猜你喜欢
随机推荐
.NET Core 跨平台资源监控库及 dotnet tool 小工具
Newbe.ObjectVisitor 样例 1
JVM真香系列:轻松理解class文件到虚拟机(下)
Dynamic relu: Microsoft's refreshing device may be the best relu improvement | ECCV 2020
[cloud service] there are so many ECS instances on alicloud server, how to select the type? Best practice note
使用Fastai开发和部署图像分类器应用
Solve the problem that the value of new date() of JS in IE and Firefox is invalid date and Nan Nan
Deep copy
Why need to use API management platform
实现图片的复制
【杂谈】JS相关的线程模型整理
快来看看!AQS 和 CountDownLatch 有怎么样的关系?
RSA asymmetric encryption algorithm
CMS garbage collector
APReLU:跨界应用,用于机器故障检测的自适应ReLU | IEEE TIE 2020
Regular backup of WordPress website program and database to qiniu cloud
Part 1 - Chapter 2 pointer operation
Flink系列(0)——准备篇(流处理基础)
An online accident caused by improper use of thread pool
200人的程序员面试经验,都在这里了