当前位置:网站首页>Single case of hungry and lazy mode
Single case of hungry and lazy mode
2022-06-25 02:58:00 【Bugxiu_ fu】
Today, I'd like to share a few ways to write the single example mode , And the implementation code of the abstract factory , I hope I can help you all .
1. Why you need to learn design patterns
Design patterns (Design pattern) Represents best practice , It is the experience summary of many excellent software developers , A solution to a particular problem . It is not a grammatical rule , Nor is it tied to a particular language . The reusability of code can be improved by using design patterns properly , Maintainability , Extensibility , Robustness and security , These are very important non functional requirements of the system .
2、 Common design patterns
2.1 The singleton pattern
Concept : Ensure that only one instance is in memory
effect : Management of system configuration files , These configuration files can be read and written using a singleton object , When configuration information is needed elsewhere in the system , Just use the singleton object to get it , This facilitates unified management of configuration information .
advantage :
There is only one object in memory , Save memory space ;
Avoid frequent creation of destroyed objects , Can improve performance ;
Avoid multiple use of shared resources , Simplify access ;
Provide a global access point for the whole system .
shortcoming :
Not for objects that change frequently ;
Abuse of single case will bring some negative problems , For example, in order to save resources, the database connection pool object is designed as a single instance class , May cause too many programs sharing connection pool objects to overflow connection pool ;
Case study
1、 Hunger mode
This straight line method is simple , And it's thread safe .
/** * The singleton pattern , Hunger is loaded */ public class SingletonDemo { //1. You need to have a private constructor , Prevent this class from passing new To create an instance private SingletonDemo(){} //2. Hunger mode , First, generate an instance private static final SingletonDemo instance = new SingletonDemo(); //3. Static methods , Used to get the generated instance public static SingletonDemo getInstance() { return instance; } public String hello(String name) { return "hello " + name; } }2、 The sluggard model
It can guarantee the singleton , And thread safety ( The outer class is singleton ; It's only going to be executed once )
When an external class calls a static method , Load only external classes ; When the static method accesses the properties of the inner class , Will load instances of static inner classes .
The first way to write it
/** * The singleton pattern : Lazy loading , Thread safety */ public class SingletonDemo04 { // Prevent external instantiation private SingletonDemo04(){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } // Use a static inner class to use a SingletonDemo04 object private static class SingletonDemoHolder { private final static SingletonDemo04 instance = new SingletonDemo04(); } public static SingletonDemo04 getInstance() { return SingletonDemoHolder.instance; } public String hello(String name) { return "hello " + name; } }The second way ( enum )
public enum SingletonDemo05 { INSTANCE; public String hello(String name) { return "hello " + name; } }2.2 Factory mode
effect
The reason for using the factory is that we can use the factory mode , To centrally control the creation process of objects , This can bring more flexibility to the design ; Column spring Of IOC A container is a classic implementation of the factory pattern
The illustration
Used to produce the specified series of objects . Take the duck as an example , Ducks have real ducks , Rubber duck , Electronic toy duck, etc . How to easily create a variety of ducks , And control the creation process , To facilitate future maintenance and expansion ?
2.3 Abstract factory
Used to generate the specified product family , A product family includes multiple products . for example : We are all familiar with computer manufacturing related industries , Yes HP, Logitech , lenovo , Dell , In recent years, Huawei , Xiaomi also came in , Each manufacturer's computer also includes a mouse , keyboard , Screen and other accessories . At this point, we need to use the factory pattern to manage different product families , Use a simple factory ( There is also a method called the factory method ) It has been unable to meet the requirements , You can use an abstract factory at this point
Code
PcFactory Factory
public abstract class PcFactory { public abstract Mouse makeMouse(); public abstract Keyboard makeKeyboard(); private static HpFactory hpFactory = new HpFactory(); private static LogicFactory logicFactory = new LogicFactory(); public final static int PC_TYPE_HP = 1; public final static int PC_TYPE_LG = 2; public static PcFactory getPcFactory(int pcType) { switch (pcType){ case 1: return hpFactory; case 2 : return logicFactory; default: return null; } }Mouse class
public abstract class Mouse { abstract String getInfo(); }Hpkeyboard class
public class HpKeyboard extends Keyboard { @Override String getInfo() { return "HP keyboard"; } }2.4 The chain of responsibility model
effect
web The filter in the container is a classic scenario of the responsibility chain pattern . Another example : When submitting content on the Forum , The forum system needs to process some keywords , See if there are any sensitive words , We can use the responsibility chain model to deal with these sensitive words .
2.5 Observer mode (Obsever)
![]()
effect
Classic usage scenarios , such as :java Medium swing Handling of events in the package . Browser to mouse , Handling of keyboard and other events , spring The event publishing mechanism in also uses this pattern .
边栏推荐
猜你喜欢

Before the age of 36, Amazon transgender hackers were sentenced to 20 years' imprisonment for stealing data from more than 100million people!

使用ShaderGraph制作边缘融合粒子Shader的启示

Performance rendering of dSPACE

After reciting the eight part essay, I won the hemp in June
![Planification du réseau | [quatre couches de réseau] points de connaissance et exemples](/img/c3/d7f382409e99eeee4dcf4f50f1a259.png)
Planification du réseau | [quatre couches de réseau] points de connaissance et exemples

高速缓存Cache详解(西电考研向)

DSPACE set zebra crossings and road arrows

分布式事务解决方案和代码落地

XML建模

Random list random generation of non repeating numbers
随机推荐
ERROR日志格式与注意点
Getting started with unityshader Essentials - PBS physics based rendering
ACM. Hj70 matrix multiplication calculation amount estimation ●●
[analysis of STL source code] functions and applications of six STL components (directory)
Using qdomdocument to manipulate XML files in QT
运行时修改Universal Render Data
Egg 服务搭建微信公众号的基础服务
Uncaught Error: [About] is not a <Route> component. All component children of <Routes> must be a <Ro
Wechat applet obtains the parameters carried after scanning the QR code
高数 | 精通中值定理 解题套路汇总
在Microsoft Exchange Server 2007中安装SSL证书的教程
計網 | 【四 網絡層】知識點及例題
Easy to use dictionary -defaultdict
调用系统函数安全方案
MySQL command backup
Is it safe for Guoxin golden sun to open an account in the steps of opening new bonds
14 bs对象.节点名称.name attrs string 获取节点名称 属性 内容
PE文件基础结构梳理
How to click DOM to automatically locate the corresponding code line in vscode
How to uninstall CUDA


