当前位置:网站首页>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 .
边栏推荐
- Go synchronization waiting group
- Modifying universal render data at runtime
- Doak CMS article management system recommendation
- DSPACE设置斑马线和道路箭头
- 高速缓存Cache详解(西电考研向)
- DSPACE的性能渲染问题
- MATLAB主窗口与编辑器窗口分开为两个界面的解决办法
- 高数 | 精通中值定理 解题套路汇总
- Advanced mathematics | proficient in mean value theorem problem solving routines summary
- Dirvish Chinese document of vim
猜你喜欢

14 BS object Node name Name attrs string get node name attribute content

The era of copilot free is over! Student party and defenders of popular open source projects can prostitute for nothing

Leetcode 210: curriculum II (topological sorting)

PyTorch学习笔记(七)------------------ Vision Transformer

nacos实践记录

計網 | 【四 網絡層】知識點及例題

Unity存档系统——Json格式的文件

Once beego failed to find bee after passing the go get command Exe's pit
![[STL source code analysis] configurator (to be supplemented)](/img/87/0ed1895e9cdb5327411c0c9cb0197f.png)
[STL source code analysis] configurator (to be supplemented)

After reciting the eight part essay, I won the hemp in June
随机推荐
软件测试周刊(第77期):只要放弃一次,就会滋生放弃的习性, 原本可以解决的问题也会变得无法解决。
Wechat applet obtains the parameters carried after scanning the QR code
国信金太阳打新债步骤 开户是安全的吗
[i.mx6ul] u-boot migration (VI) network driver modification lan8720a
小米路由R4A千兆版安装breed+OpenWRT教程(全脚本无需硬改)
AOSP ~ 默认属性值
AOSP ~ WIFI架构总览
Processon producer process (customized)
MATLAB主窗口与编辑器窗口分开为两个界面的解决办法
doak-cms 文章管理系统 推荐
怎么开户打新债 开户是安全的吗
Go synchronization waiting group
Planification du réseau | [quatre couches de réseau] points de connaissance et exemples
Insurance can also be bought together? Four risks that individuals can pool enough people to buy Medical Insurance in groups
Network planning | [four network layers] knowledge points and examples
@PostConstruct
ACM. Hj75 common substring calculation ●●
Once beego failed to find bee after passing the go get command Exe's pit
好用的字典-defaultdict
Expressing the transformation of two coordinate systems with vectors


