当前位置:网站首页>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 .
边栏推荐
- QT package the EXE file to solve the problem that "the program input point \u zdapvj cannot be located in the dynamic link library qt5cored.dll"
- LeetCode 210:课程表 II (拓扑排序)
- Call system function security scheme
- @PostConstruct
- 計網 | 【四 網絡層】知識點及例題
- 计算机三级(数据库)备考题目知识点总结
- Getting started with unityshader - Surface Shader
- New solution of 202112-2 sequence query
- ACL access control of squid proxy server
- Unity存档系统——Json格式的文件
猜你喜欢
AI clothing generation helps you complete the last step of clothing design
记一次beego通过go get命令后找不到bee.exe的坑
DSPACE设置斑马线和道路箭头
[STL source code analysis] configurator (to be supplemented)
DSPACE的性能渲染问题
Leecode learning notes - the shortest path for a robot to reach its destination
软件测试周刊(第77期):只要放弃一次,就会滋生放弃的习性, 原本可以解决的问题也会变得无法解决。
小米路由R4A千兆版安装breed+OpenWRT教程(全脚本无需硬改)
Distributed transaction solutions and code implementation
automated testing
随机推荐
好用的字典-defaultdict
调用系统函数安全方案
Charles packet capturing tool
Performance rendering of dSPACE
Unity archive system - file in JSON format
New solution of 202112-2 sequence query
用向量表示两个坐标系的变换
软件测试周刊(第77期):只要放弃一次,就会滋生放弃的习性, 原本可以解决的问题也会变得无法解决。
计算机三级(数据库)备考题目知识点总结
Computer wechat user picture decoded into picture in DAT format (TK version)
Enlightenment of using shadergraph to make edge fusion particle shader
PSQL column to row
@PostConstruct
Once beego failed to find bee after passing the go get command Exe's pit
Error log format and precautions
Pytorch learning notes (VII) ------------------ vision transformer
国信金太阳打新债步骤 开户是安全的吗
CMakeLists中的add_definitions()函数
MySql安装教程
36岁前亚马逊变性黑客,窃取超1亿人数据被判20年监禁!