Design Mode: Metadata Mode
In the Structural mode, how to design static structures between objects and how to complete inheritance, implementation, and dependency between objects is related to whether the system design is robust (robust ): such as easy to understand, easy to maintain, easy to modify, low coupling, and so on. The Structural mode, just like its name, provides the relational structures of various objects applicable to different occasions.
- Default Adapter mode Bridge Mode Composite mode Decorator mode Facade mode Flyweight mode Proxy Mode
The metadata mode is used to reduce the number of objects created and improve program performance. in java, the String mode uses the metadata mode, that is, if the object content is the same, no new object is created. If there is no object with the same content, a new object is created.
String str1 = abc ;String str2 = abc ;System.out.println(str1==str2) ;
The above code outputs true, because String uses the metadata mode.
The following describes how to implement a metadata-like mode, a Shape interface Shape, and a Rectangle to implement the Shape interface. We asked the client to create rectangles of different colors. The class structure diagram is as follows:
Shape Interface
public interface Shape { public void draw() ;}
Rectangle class
public class Rectangle implements Shape { private int width, height; private String color; public Rectangle(String color) { this.color = color; } public void setWidth(int width) { this.width = width; } public void setHeight(int height) { this.height = height; } @Override public void draw() { System.out.println(width: + width + height: + height + color: + color); }}
ShapeFactory class
public class ShapeFactory { private static HashMap
hs = new HashMap
() ; public static Shape getShape(String color){ Shape shape = hs.get(color); if(shape==null){ shape = new Rectangle(color) ; hs.put(color, shape) ; } return shape; } public static int size(){ return hs.size() ; }}
Client class
public class Client { private static String[] colors = { red, blue, yellow, green, black }; public static void main(String[] args) { Rectangle rectangle = null ; for (int i=0;i<20;i++) { rectangle = (Rectangle) ShapeFactory.getShape(getRandomColor()); rectangle.setHeight(i); rectangle.setWidth(i); rectangle.draw(); } System.out.println(ShapeFactory.size()) ; //always 5 } private static String getRandomColor() { return colors[(int) (Math.random() * colors.length)]; }}