current position:Home>Software design pattern -- Chapter 3 structural pattern -- sharing element pattern
Software design pattern -- Chapter 3 structural pattern -- sharing element pattern
2022-04-29 14:34:48【Orange security】
Catalog
Chapter two Structural mode
1、 An overview of structural models
Structural patterns describe how classes or objects are organized into larger structures in a certain layout .
- Class structure pattern : use
Inheritance mechanism
To organize interfaces and classes , - Object structured mode : use
Combine or aggregate
To combine objects . - Because the coupling degree of combination relation or aggregation relation is lower than that of inheritance relation , Satisfy “ Synthetic multiplexing principle ”, So object structured pattern is more flexible than class structured pattern .
The structure is divided into the following types 7 Kind of :
agent (Proxy) Pattern : The client accesses the object indirectly through a proxy , To limit 、 Enhance or modify some properties of the object .
Adapter (Adapter) Pattern : Convert the interface of one class to another that the customer wants , Make the classes that can't work together because of the interface incompatibility work together .
The bridge (Bridge) Pattern : take
Separation of abstraction and implementation
, So that they can change independently . It is realized by replacing inheritance relationship with composition relationship , This reduces abstraction and implementation 2 Coupling degree of variable dimensions .decorate (Decorator) Pattern : Dynamically give objects
Add some responsibilities
, That is to add its extra functions .appearance (Facade) Pattern : For multiple complex subsystems
Provide a consistent interface
, Make these subsystems more accessible .Enjoying yuan (Flyweight) Pattern : Use sharing technology to effectively
Support a large number of fine-grained Reuse of objects
.Combine (Composite) Pattern :
Combine objects into a tree hierarchy
, Make users have consistent access to single and composite objects .
notes : above 7 A structural pattern , except Adapter pattern It is divided into class structured pattern and object structured pattern 2 Kind of , The rest are all object structured patterns .
2、 The flyweight pattern
In the process of object-oriented programming , Sometimes there is the problem of creating a large number of instances of the same or similar objects . Creating so many objects will consume a lot of system resources , It's a bottleneck in system performance .
Such as : Black and white pieces in go and Gobang , Coordinate points or colors in the image , Router in LAN 、 Switches and hubs , Desks and stools in the classroom and so on . These objects have many similarities , If you can extract the same parts and share them , It can save a lot of system resources , This is the background of Xiangyuan mode .
(1) The definition and characteristics of patterns
Definition
ApplicationSharing Technology
To effectively support the reuse of a large number of fine-grained objects .
It does this by sharing objects that already existSignificantly reduce the number of objects that need to be created
、Avoid the overhead of a large number of similar objects
, So as to improve the utilization rate of system resources .advantage
(1) Greatly reduce the number of similar or identical objects in memory , Save system resources , Provide system performance ( Cache object )
(2) The external state in the meta mode is relatively independent , And does not affect the internal state ( Color modification , Does not affect graphics )shortcoming
To make objects shareable , You need to externalize part of the state of the meta object , Separate the internal state from the external state , Complicate program logic
(2) The structure and implementation of patterns (Flyweight )
Enjoying yuan (Flyweight ) There are two states in the pattern :
- Internal state , That is, shareable parts that will not change with the environment .
- External state , It refers to the unshareable part that changes with the environment . The key to the implementation of the sharing mode is to distinguish the two states in the application , And externalize the external state .
- structure
Abstract meta roles (Flyweight):
(1) It's usually an interface or an abstract class , In an abstract metaclassDeclare the public method of the concrete meta class
,These methods can provide the internal data of the sharing object to the outside world ( Internal state )
.
(2) You can also use these methods to set up external data ( External state ).Enjoy the specific yuan (Concrete Flyweight) role :
(1) It implements the abstract primitive class , It's called a meta object ;
(2) It provides storage space for the internal state in the specific primitive class .
(3) Usually, we can design a specific primitive class in combination with the singleton pattern , Provide a unique sharing object for each specific sharing element class .Non enjoyment yuan (Unsharable Flyweight) role :
(1) Not all subclasses of the abstract sharing metaclass need to be shared ,Subclasses that cannot be shared can be designed as non shared concrete sharing metaclasses
;
(2) When an object of unshared concrete sharer class is needed, it can be created directly by instantiation .The flyweight factory (Flyweight Factory) role :
(1)Responsible for creating and managing the shareware roles
.
(2) When a client object requests a sharing object , Check whether there are qualified sharing objects in the system , If it exists, provide it to the customer ;
(3) If it doesn't exist , Create a new share object .
- Realization
example : tetris
In the game of Tetris , Each different box is an instance object , These objects take up a lot of memory space , The following is implemented using the shared element mode .
The code is as follows :
Tetris has different shapes , We can take these shapes up AbstractBox, Attributes and behaviors used to define commonalities .
Abstract meta roles :AbstractBox
public abstract class AbstractBox {
// Get shape
public abstract String getShape();
// Display graphics and colors , Transfer external status
public void display(String color) {
System.out.println(" Square shape :" + this.getShape() + " Color :" + color);
}
}
The next step is to define different shapes ,IBox class 、LBox class 、OBox Class etc. .
Specific enjoy yuan role
public class IBox extends AbstractBox {
@Override
public String getShape() {
return "I";
}
}
public class LBox extends AbstractBox {
@Override
public String getShape() {
return "L";
}
}
public class OBox extends AbstractBox {
@Override
public String getShape() {
return "O";
}
}
Provides a factory class (BoxFactory), Used to manage meta objects ( That is to say AbstractBox Subclass object ), The factory class object only needs one , So you can use singleton mode . And give factory class a way to get shape .
The flyweight factory :BoxFactory
public class BoxFactory {
// Aggregating meta roles
private static HashMap<String, AbstractBox> map;
// Initialize in constructor
private BoxFactory() {
map = new HashMap<String, AbstractBox>();
AbstractBox iBox = new IBox();
AbstractBox lBox = new LBox();
AbstractBox oBox = new OBox();
map.put("I", iBox);
map.put("L", lBox);
map.put("O", oBox);
}
// Provide a method to get the factory class object
public static BoxFactory getInstance() {
return factory;
}
// Create a meta factory in singleton mode
private static BoxFactory factory = new BoxFactory();
// Get the meta object by name
public AbstractBox getBox(String key) {
return map.get(key);
}
}
Test class :
public class Client {
public static void main(String[] args) {
// obtain I Graphic objects
AbstractBox box1 = BoxFactory.getInstance().getShape("I");
box1.display(" gray ");
// obtain L Graphic objects
AbstractBox box2 = BoxFactory.getInstance().getShape("L");
box2.display(" green ");
// obtain O Graphic objects
AbstractBox box3 = BoxFactory.getInstance().getShape("O");
box3.display(" gray ");
// obtain O Graphic objects
AbstractBox box4 = BoxFactory.getInstance().getShape("O");
box4.display(" Red ");
System.out.println(" Two times O Whether the drawing object is the same object :" + (box3 == box4));
}
(3) Application scenarios
- A system has a large number of identical or similar objects , Cause a lot of memory consumption .
- Most of the state of an object can be externalized , You can pass these external states into the object .
- When using the sharing mode, you need to maintain a sharing pool for storing sharing objects , And it takes a certain amount of system resources , therefore , It should be worth using the sharable mode when you need to reuse the sharable object multiple times .
(4) Expand
Integer Class uses the meta pattern . Let's look at the following example :
public class Demo {
public static void main(String[] args) {
Integer i1 = 127;
Integer i2 = 127;
System.out.println("i1 and i2 Whether the object is the same object ?" + (i1 == i2));
Integer i3 = 128;
Integer i4 = 128;
System.out.println("i3 and i4 Whether the object is the same object ?" + (i3 == i4));
}
}
Run the above code , give the result as follows :
Why the first output statement outputs true, The second output statement outputs false?
because Integer
By default, create and cache first -128 ~ 127
Between Integer
object , When calling valueOf
If the parameter is in -128 ~ 127
Between, the subscript is calculated and returned from the cache , Otherwise create a new Integer
object .
Simple sharing mode , In this sharing mode, all specific sharing classes can be shared , There is no specific sharing element class that is not shared
Compound sharing mode , In this sharing mode, some sharing objects are composed of simple sharing objects , They are the composite sharing objects . Although the composite sharing object itself cannot share , But they can be broken down into simple sharing objects and then shared
copyright notice
author[Orange security],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291302397154.html
The sidebar is recommended
- Event handling of react
- Character coding knowledge that needs to be understood in front-end development
- 05. JavaScript operator
- 06. JavaScript statement
- Vue basics and some components
- Introduction to front-end Er excellent resources
- Node. Summary of methods of outputting console to command line in JS
- The beginning of passion, the ending of carelessness, python anti climbing, Jiageng, friends asked for MIHA's API and arranged y24 for him
- Technology sharing | test platform development - Vue router routing design for front-end development
- Node under windows JS installation detailed steps tutorial
guess what you like
Layui built-in module (element common element operation)
Excuse me, my eclipse Exe software has clearly opened to display the number of lines. Why is it useless
It was revealed that Meila of Sea King 2 had less than ten minutes to appear, which was affected by negative news
Vue element admin how to modify the height of component El tabs
Bootstrap navigation bar drop-down menu does not take effect
Vue Preview PDF file
Geely joined the hybrid sedan market, and Toyota seemed even more hopeless
Mustache template engine for exploring Vue source code
Referer and referer policy and picture anti-theft chain
Explain the "three handshakes" and "four waves" of TCP connection in detail
Random recommended
- Introduction to basic methods of math built-in objects in JavaScript
- JavaWeb Tomcat (III) httpservlet
- Vue Za wiper technical scheme
- Differences, advantages and disadvantages between HTTP negotiation cache Etag and last modified
- After taking tens of millions less, the management of Lenovo holdings took the initiative to reduce the salary by 70%
- What if Vue introduces this file and reports an error?
- Use Hikvision Web3 in vue3 2. Live broadcast without plug-in version (II)
- How to learn high-order function "zero basis must see"
- Detailed explanation of JS promise
- Cesium drawcommand [1] draw a triangle without talking about the earth
- The role of webpack cli in webpack packaging
- Action system of coco2d-x-html5
- Vxe table check box paging data memory selection problem
- [hand tear series] hand tear promise -- this article takes you to realize promise perfectly according to promise a + specification!
- QT use qdialog to realize interface mask (mask)
- Differences between JSP comments and HTML comments
- Bankless: Ethereum's data report and ecological highlights in the first quarter of 22 years
- Spring mvc07: Ajax research
- Understand the basic history and knowledge of HTTP
- JQuery realizes picture switching
- Technology sharing | learning to do test platform development vuetify framework
- Technology sharing | test platform development - Vue router routing design for front-end development
- Return to the top - wepy applet - front end combing
- Install less / sass
- Node. JS basic tutorial
- Have you learned how to use Vue?
- The front end can't calm me down
- Introduction to JavaScript
- Vue
- Technology sharing | learning to do test platform development vuetify framework
- Vue starts with an error and prompts NPM install core- [email protected] // oryarn add core- [email protected]
- STM32 + esp8266 + air202 basic control chapter - 201 - server reverse proxy - server installation nginx (. Windows system)
- STM32 + esp8266 + air202 basic control chapter - 205 - server reverse proxy - Web server configuration HTTPS access (. Windows system)
- Element after the spring frame assembly is opened, the scroll bar returns to the top
- Java project: nursing home management system (java + springboot + thymeleaf + HTML + JS + MySQL)
- Java project: drug management system (java + springboot + HTML + layui + bootstrap + seals + MySQL)
- What are the similarities and differences between jQuery and native JS?
- The starting price is less than 90000 yuan, and the National University's seven seat super value SUV xinjietu x70s is officially pre sold
- Fastadmin modifies the list width (limit the list width, support CSS writing), and the width limit. It is too large or useless.
- Learning ajax in Vue is enough