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:48Orange security

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 :

  1. agent (Proxy) Pattern : The client accesses the object indirectly through a proxy , To limit 、 Enhance or modify some properties of the object .

  2. 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 .

  3. 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 .

  4. decorate (Decorator) Pattern : Dynamically give objects Add some responsibilities , That is to add its extra functions .

  5. appearance (Facade) Pattern : For multiple complex subsystems Provide a consistent interface , Make these subsystems more accessible .

  6. Enjoying yuan (Flyweight) Pattern : Use sharing technology to effectively Support a large number of fine-grained Reuse of objects .

  7. 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

  1. Definition
    Application Sharing Technology To effectively support the reuse of a large number of fine-grained objects .
    It does this by sharing objects that already exist Significantly 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 .

  2. 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 )

  3. 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 .

  1. structure
  • Abstract meta roles (Flyweight):
    (1) It's usually an interface or an abstract class , In an abstract metaclass Declare 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 .

 Insert picture description here

  1. 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 .

 Insert picture description here

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 {

    public String getShape() {
        return "I";

public class LBox extends AbstractBox {

    public String getShape() {
        return "L";

public class OBox extends AbstractBox {

    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 :
 Insert picture description here
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
     Insert picture description here

  • 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
     Insert picture description here

copyright notice
author[Orange security],Please bring the original link to reprint, thank you.

Random recommended