The adorner pattern can dynamically add capabilities to existing objects. Next, I'll use a simple example to illustrate how to use the decorator pattern in a program.
1. Decorator Mode
Let's assume that you're looking for a girlfriend. There are a lot of girls from different countries, such as: The United States, China, Japan, France and so on, each of them have a unique personality and hobbies, if you need to simulate such a situation in the program, assuming that every girl is a Java class, then there will be thousands of classes, This can cause the expansion of the class, and the scalability of such a design will be relatively poor. Because if we need a new girl, we need to create a new Java class, which in fact violates the OCP (open to extension, closed to modify) principles that need to be followed in program development.
Let's redesign another design so that each personality or hobby becomes a decoration that can be dynamically added to every girl.
2. Class Diagram structure
3. Decorator Pattern Sample Code
Girl.java
Copy Code code as follows:
Public abstract class Girl {
String Description = "no particular";
Public String getdescription () {
return description;
}
}
Americangirl.java
Copy Code code as follows:
public class Americangirl extends Girl {
Public Americangirl () {
Description = "+american";
}
}
Europeangirl.java
Copy Code code as follows:
public class Europeangirl extends Girl {
Public Europeangirl () {
Description = "+european";
}
}
Girldecorator.java
Copy Code code as follows:
Public abstract class Girldecorator extends Girl {
Public abstract String getdescription ();
}
Science.java
Copy Code code as follows:
public class Science extends Girldecorator {
Private Girl Girl;
Public Science (Girl Girl) {
This.girl = Girl;
}
@Override
Public String getdescription () {
return this.girl.getDescription () + "+like science";
}
public void Caltulatestuff () {
System.out.println ("Scientific calculation!");
}
}
Art.java
Copy Code code as follows:
public class Art extends Girldecorator {
Private Girl Girl;
Public Art (Girl Girl) {
This.girl = Girl;
}
@Override
Public String getdescription () {
return this.girl.getDescription () + "+like Art";
}
public void Draw () {
System.out.println ("Draw pictures!");
}
}
Main.java
Copy Code code as follows:
public class Main {
public static void Main (string[] args) {
Ordinary American Girl
Girl G1 = new Americangirl ();
System.out.println (G1.getdescription ());
Like science.
Science g2 = new Science (g1);
System.out.println (G2.getdescription ());
Like the art of
Art G3 = new Art (G2);
System.out.println (G3.getdescription ());
}
}
4. The application of decorator pattern in JDK
Io in Java is the most typical example of an adorner pattern.
The following is a simple example of decorating a InputStreamReader object with a BufferedReader object:
Copy Code code as follows:
BufferedReader input = new BufferedReader (new InputStreamReader (system.in));
System.in is an InputStream object
(End of full text)