“This is the 14th day of my participation in the First Challenge 2022.
define
Decorator pattern: Dynamically attaching functions to objects without changing the original objects, providing a more flexible alternative to inheritance, and embodiments the open and closed principle
case
demand
A guy goes to a coffee shop and orders a cappuccino with hot milk
plan
Define the coffee base class
public abstract class Coffee {
private String desc;
private float price;
public abstract float cost(a);
public String getDesc(a) {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public float getPrice(a) {
return price;
}
public void setPrice(float price) {
this.price = price; }}Copy the code
Defines a cappuccino coffee class that inherits the coffee base class
public class Cappuccino extends Coffee{
public Cappuccino(a){
setDesc("Ordered a cappuccino.");
setPrice(100);
}
@Override
public float cost(a) {
System.out.println("Current price is:" + super.getPrice());
return super.getPrice(); }}Copy the code
Define the decorator class
public class Decorator extends Coffee{
private Coffee coffee;
public Decorator(Coffee coffee){
this.coffee = coffee;
}
@Override
public float cost(a) {
return super.getPrice() + this.coffee.cost();
}
@Override
public String getDesc(a) {
return super.getDesc() + coffee.cost(); }}Copy the code
Define the hot milk class
public class HotMilk extends Decorator {
public HotMilk(Coffee coffee){
super(coffee);
setPrice(200);
setDesc("Ordered a glass of hot milk."); }}Copy the code
Defining test classes
Public class Test {public static void main(String[] args) {public static void main(String[] args) = new Cappuccino(); System.out.println(coffee.getDesc()); //System.out.println(coffee.getPrice()); System.out.println(coffee.cost());; HotMilk hotMilk = new HotMilk(coffee); System.out.println(hotMilk.getDesc()); //System.out.println(hotMilk.getPrice()); System.out.println(hotMilk.cost()); }}Copy the code
Viewing test results
Analysis of the
Decorator pattern is also for the purpose of extending the function of the object, is an alternative to inheritance pattern, can dynamically extend the function of an implementation class, decorator class and decorator class can be independent of each other, not coupled, flexible and convenient.
Usage scenarios
- When you need to add responsibilities to an existing class that cannot be extended by subclassing it,
- When you need to combine an existing set of basic functions, it can produce a lot of functions
- When an object’s functionality requires it to be added dynamically, or removed dynamically
trailer
Stay tuned for the next installment as we examine composition patterns
Need source code can pay attention to the public number [review old know new Java], more work to share with you.