当前位置:网站首页>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 .
边栏推荐
猜你喜欢
随机推荐
New solution of 202112-2 sequence query
Getting started with unityshader - Surface Shader
好用的字典-defaultdict
Is it safe to open an account by fraud
爱
分布式事务解决方案和代码落地
打新债是不是骗局 开户是安全的吗
Computer wechat user picture decoded into picture in DAT format (TK version)
Migrate Oracle database from windows system to Linux Oracle RAC cluster environment (1) -- migrate data to node 1
AOSP ~ WIFI架构总览
Can the polardb database be connected to the data source through MySQL
微信小程序获取扫描二维码后携带的参数
How to click DOM to automatically locate the corresponding code line in vscode
F - spices (linear basis)
Solution of separating matlab main window and editor window into two interfaces
ERROR日志格式与注意点
AI服装生成,帮你完成服装设计的最后一步
Summary of stack frame in arm assembly
Mall project pc--- product details page
Array - fast and slow pointer in one breath












