当前位置:网站首页>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 .
边栏推荐
猜你喜欢

vie的刷新机制

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

MySQL learning notes -- addition, deletion, modification and query on a single table

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

Performance rendering of dSPACE

Introduction to CUDA Programming minimalist tutorial

Computer wechat user picture decoded into picture in DAT format (TK version)

支付宝被风控7天怎么办?付解决方案

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

Copilot免费时代结束!学生党和热门开源项目维护者可白嫖
随机推荐
C#实现水晶报表绑定数据并实现打印
消息称一加将很快更新TWS耳塞、智能手表和手环产品线
Difference between left join on and join on
Go synchronization waiting group
yarn : 无法加载文件 C:\Users\xxx\AppData\Roaming\npm\yarn.ps1,因为在此系统上禁止运行脚本
AI服装生成,帮你完成服装设计的最后一步
高数 | 精通中值定理 解题套路汇总
Is it safe for Guoxin golden sun to open an account in the steps of opening new bonds
把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(2)——将数据库转换为集群模式
目录权限错误导致 Oracle 11g rac 集群数据库无法启动的问题
软件测试周刊(第77期):只要放弃一次,就会滋生放弃的习性, 原本可以解决的问题也会变得无法解决。
20 years ICPC Macau station L - random permutation
计网 | 【四 网络层】知识点及例题
@PostConstruct
Solution of separating matlab main window and editor window into two interfaces
ACM. HJ75 公共子串计算 ●●
Internship: use of SVN
ACM. HJ70 矩阵乘法计算量估算 ●●
Call system function security scheme
Planification du réseau | [quatre couches de réseau] points de connaissance et exemples


