java design pattern --- decorative pattern

1. Decoration mode: Add some extra responsibilities to an object dynamically. In terms of adding functions, decoration mode is more flexible than generating subclasses.

2. Benefits: Remove the decorative functions in the class from the class, effectively separate the core responsibilities of the class from the decorative functions, and remove the repeated decorative logic in the related class.

3. Role:

  (1) Abstract component role: Person (abstract class)

  (2) Specific component role: OnePerson (object to be decorated implements abstract component interface)

  (3) Decoration role: PersonDecorator (decorator, used to decorate objects to implement abstract component interface)

  (4) Specific decoration roles: RichPerson, SmartPerson, HighPerson (specific decoration content, inherit the decoration role class)

3、demo:

// Decorative mode- 
public interface Person {
public void desc ();
}

// Object to be decorated--enter name 
public class OnePerson implements Person {
private String name;

public OnePerson (String name) {
this.name = name;
}

@Override
public void desc () {
System.out.println ( "I am:" + name);
}
}

// Decorator-- used to decorate objects 
public class PersonDecorator implements Person {
private Person person;

public PersonDecorator (Person person) {
this.person = person;
}

@Override
public void desc () {
person.desc ();
}
}

public class RichPerson extends PersonDecorator {
public RichPerson(Person person) {
super(person);
}

@Override
public void desc() {
super.desc();
System.out.println("家里很富!");
}
}
public class SmartPerson extends PersonDecorator {
public SmartPerson(Person person) {
super(person);
}

@Override
public void desc() {
super.desc();
System.out.println("超级聪明!");
}
}
public class HighPerson extends PersonDecorator {

public HighPerson(Person person) {
super(person);
}

@Override
public void desc() {
super.desc();
System.out.println("长得很高!");
}
}

// Test class 
public class MainTest {

public static void main (String [] args) {

Person tom = new SmartPerson (new RichPerson (new HighPerson (new OnePerson ("tom"))));
tom.desc ();
}
}

operation result:

  I am: tom
  grows very high!
  The family is very rich!
  Super smart!







Guess you like

Origin www.cnblogs.com/tengri-fighting/p/12714453.html