Original October 29, 2017 serious Xiao Su
Introduction to decoration mode
Decoration pattern, also known as packaging pattern, is one of the structural patterns. It uses a transparent way to the client to dynamically expand the function of the object, and it is also one of the alternative schemes of inheritance relationship. (excerpt: analysis and practice of Android source code design pattern)
UML class diagram
Code practice
/**
* Created by suful on 2017/10/29.
* Define human as an abstract class
* Abstract component class is also the original object we need to decorate
*/
public abstract class Person {
/**
* The abstract way to dress
*/
public abstract void dressed();
}
/**
* Created by suful on 2017/10/29.
* Who is the specific decoration?
* Define a boy class (Boy) - "belongs to human, inheriting the method of human to implement wearing
*/
public class Boy extends Person {
@Override
public void dressed() {
System.out.println("Wearing underwear and underpants");
}
}
/**
* Created by suful on 2017/10/29.
* (Boy) Class to decorate our body object, PersonCloth
* <p>
* Clothes people wear
*/
public abstract class PersonCloth extends Person {
protected Person person;
public PersonCloth(Person person) {
this.person = person;
}
@Override
public void dressed() {
/**
* Call the dressed() / method in the person class
*/
person.dressed();
}
}
/**
* Created by suful on 2017/10/29.
* Fancy clothes
*/
public class ExpensiveCloth extends PersonCloth {
public ExpensiveCloth(Person person) {
super(person);
}
@Override
public void dressed() {
super.dressed();
dressShirt();
dressLeather();
dressJean();
}
private void dressShirt() {
System.out.println("Wear short sleeves");
}
private void dressLeather() {
System.out.println("Wear a leather coat");
}
private void dressJean() {
System.out.println("Wear a pair of jeans");
}
}
/**
* First of all, we need a boy
*/
Person person = new Boy();
/*
* And put on cheap clothes for him
* */
PersonCloth personCloth = new CheapCloth(person);
personCloth.dressed();
/*Or dress him in fancy clothes*/
PersonCloth personCloth1 = new ExpensiveCloth(person);
personCloth1.dressed();
Reference book: analysis and practice of Android source code design pattern