Patterns
patterns
[TOC]
General Patterns
- active record
- mvc
- mvvm
- state machine
- reference couting
- COW(Copy On Write)
- iterator
- 組合子邏輯
- 柯里化(英語:Currying)
- λ演算
- monod
- Curiously recurring template pattern (CRTP)
- https://en.wikipedia.org/wiki/Double-chance_function
- SOLID设计原则
- https://en.wikipedia.org/wiki/GRASP_(object-oriented_design)
并發相關
- active object
- actor model
- blockingQueue
- take
- put
-
ForkJoinPool
- execute
- future, promise, delay, deferred
- proactor
- reactor
- flow-graph
- https://en.wikipedia.org/wiki/Algorithmic_skeleton
GOF
- GoF: ref ref ref_cn ref
-
Creational 1. Simple Factory 2. Factory Method 3. Abstract Factory 4. Builder 5. Prototype 6. Singleton 7. 2.1Builder 8. 2.2Factory 9. 2.3Abstract Factory 10. 2.4Prototype 11. 2.5Singleton
Creational patterns[edit]
Name | Description | In Design Patterns | In Code Complete[13] | Other |
---|---|---|---|---|
Abstract factory | Provide an interface for creating families of related or dependent objects without specifying their concrete classes. | Yes | Yes | N/A |
Builder | Separate the construction of a complex object from its representation, allowing the same construction process to create various representations. | Yes | No | N/A |
Dependency Injection | A class accepts the objects it requires from an injector instead of creating the objects directly. | No | No | N/A |
Factory method | Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. | Yes | Yes | N/A |
Lazy initialization | Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. This pattern appears in the GoF catalog as “virtual proxy”, an implementation strategy for the Proxy pattern. | No | No | PoEAA[14] |
Multiton | Ensure a class has only named instances, and provide a global point of access to them. | No | No | N/A |
Object pool | Avoid expensive acquisition and release of resources by recycling objects that are no longer in use. Can be considered a generalisation of connection pool and thread pool patterns. | No | No | N/A |
Prototype | Specify the kinds of objects to create using a prototypical instance, and create new objects from the ‘skeleton’ of an existing object, thus boosting performance and keeping memory footprints to a minimum. | Yes | No | N/A |
Resource acquisition is initialization (RAII) | Ensure that resources are properly released by tying them to the lifespan of suitable objects. | No | No | N/A |
Singleton | Ensure a class has only one instance, and provide a global point of access to it. | Yes | Yes | N/A |
Structural patterns[edit]
Name | Description | In Design Patterns | In Code Complete[13] | Other |
---|---|---|---|---|
Adapter, Wrapper, or Translator | Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator. | Yes | Yes | N/A |
Bridge | Decouple an abstraction from its implementation allowing the two to vary independently. | Yes | Yes | N/A |
Composite | Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. | Yes | Yes | N/A |
Decorator | Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality. | Yes | Yes | N/A |
Extension object | Adding functionality to a hierarchy without changing the hierarchy. | No | No | Agile Software Development, Principles, Patterns, and Practices[15] |
Facade | Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. | Yes | Yes | N/A |
Flyweight | Use sharing to support large numbers of similar objects efficiently. | Yes | No | N/A |
Front controller | The pattern relates to the design of Web applications. It provides a centralized entry point for handling requests. | No | No | J2EE Patterns[16] PoEAA[17] |
Marker | Empty interface to associate metadata with a class. | No | No | Effective Java[18] |
Module | Group several related elements, such as classes, singletons, methods, globally used, into a single conceptual entity. | No | No | N/A |
Proxy | Provide a surrogate or placeholder for another object to control access to it. | Yes | No | N/A |
Twin [19] | Twin allows modeling of multiple inheritance in programming languages that do not support this feature. | No | No | N/A |
Behavioral patterns[edit]
Name | Description | In Design Patterns | In Code Complete[13] | Other |
---|---|---|---|---|
Blackboard | Artificial intelligence pattern for combining disparate sources of data (see blackboard system) | No | No | N/A |
Chain of responsibility | Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. | Yes | No | N/A |
Command | Encapsulate a request as an object, thereby allowing for the parameterization of clients with different requests, and the queuing or logging of requests. It also allows for the support of undoable operations. | Yes | No | N/A |
Interpreter | Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. | Yes | No | N/A |
Iterator | Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. | Yes | Yes | N/A |
Mediator | Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to vary independently. | Yes | No | N/A |
Memento | Without violating encapsulation, capture and externalize an object’s internal state allowing the object to be restored to this state later. | Yes | No | N/A |
Null object | Avoid null references by providing a default object. | No | No | N/A |
Observer or Publish/subscribe | Define a one-to-many dependency between objects where a state change in one object results in all its dependents being notified and updated automatically. | Yes | Yes | N/A |
Servant | Define common functionality for a group of classes. The servant pattern is also frequently called helper class or utility class implementation for a given set of classes. The helper classes generally have no objects hence they have all static methods that act upon different kinds of class objects. | No | No | N/A |
Specification | Recombinable business logic in a Boolean fashion. | No | No | N/A |
State | Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. | Yes | No | N/A |
Strategy | Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. | Yes | Yes | N/A |
Template method | Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. | Yes | Yes | N/A |
Visitor | Represent an operation to be performed on the elements of an object structure. Visitor lets a new operation be defined without changing the classes of the elements on which it operates. | Yes | No | N/A |
Concurrency patterns[edit]
Name | Description | In POSA2[20] | Other |
---|---|---|---|
Active Object | Decouples method execution from method invocation that reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests. | Yes | N/A |
Balking | Only execute an action on an object when the object is in a particular state. | No | N/A |
Binding properties | Combining multiple observers to force properties in different objects to be synchronized or coordinated in some way.[21] | No | N/A |
Compute kernel | The same calculation many times in parallel, differing by integer parameters used with non-branching pointer math into shared arrays, such as GPU-optimized Matrix multiplication or Convolutional neural network. | No | N/A |
Double-checked locking | Reduce the overhead of acquiring a lock by first testing the locking criterion (the ‘lock hint’) in an unsafe manner; only if that succeeds does the actual locking logic proceed.Can be unsafe when implemented in some language/hardware combinations. It can therefore sometimes be considered an anti-pattern. | Yes | N/A |
Event-based asynchronous | Addresses problems with the asynchronous pattern that occur in multithreaded programs.[22] | No | N/A |
Guarded suspension | Manages operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed. | No | N/A |
Join | Join-pattern provides a way to write concurrent, parallel and distributed programs by message passing. Compared to the use of threads and locks, this is a high-level programming model. | No | N/A |
Lock | One thread puts a “lock” on a resource, preventing other threads from accessing or modifying it.[23] | No | PoEAA[14] |
Messaging design pattern (MDP) | Allows the interchange of information (i.e. messages) between components and applications. | No | N/A |
Monitor object | An object whose methods are subject to mutual exclusion, thus preventing multiple objects from erroneously trying to use it at the same time. | Yes | N/A |
Reactor | A reactor object provides an asynchronous interface to resources that must be handled synchronously. | Yes | N/A |
Read-write lock | Allows concurrent read access to an object, but requires exclusive access for write operations. | No | N/A |
Scheduler | Explicitly control when threads may execute single-threaded code. | No | N/A |
Thread pool | A number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. Can be considered a special case of the object pool pattern. | No | N/A |
Thread-specific storage | Static or “global” memory local to a thread. | Yes | N/A |
C++
-
Modern C++ patterns ref
- RAII everywhere, so everything that holds a resource is an object that uses RAII. If you find a new/delete at all, then it’s in the same place.
- Plain functions instead of factories, singletons etc.
- Inheritance not more than 1 layer deep and from mostly abstract base classes only (except for simple “helper” methods)
- Composition over inheritance
- Think if inheritance and polymorphism is really able to completely abstract the implementations you need. Not rarely you’ll find the abstraction to be leaky and at some point you’ll have to find out, which subclass the thing you have is - at runtime. Or one of the subclass can not reasonable implement one of methods. This then often ends up with methods returning dummy values, null, throwing an “operation not supported” exception or something similar
- Avoid “function pointer/lambda/polymorphism-magic” as much as possible. In most cases when I see a function/method-call I would like to know what it actually calls at compile-time, not at run-time 這個不是很贊同,因爲DI(Dependency Injection)是一個公認的decouple的手段。函數指針會使抽象程度增加,但這是爲了封裝和維護性
- “Immutability as the default” is something I still struggle with, but try to adopt for future code I write
- If immutability is not an option, data structures where data is only added but never removed also helps
-
Basic:
- RTTI
- Virtual functions
- shared_ptr etc
- Templates
- Virtual inheriting
- Variadic macros
Also useful:
- Attributes (it depends on your compiler)
- Variadic templates
- Variadic functions
- Constexpr (sorting in compile time / calculating hash of strings etc… but the latter is related to the last section)
- Lambdas
Useful for brainfucking or in special cases:
- CRTP
- SFINAE
- inable_if (type traits)
- Foreach macro
- User-defined literals
More C++ Idioms
- Address Of
- Algebraic Hierarchy
- Attach by Initialization
- Attorney-Client
- Barton-Nackman trick
- Base-from-Member
- Boost mutant
- Calling Virtuals During Initialization
- Capability Query
- Checked delete
- Clear-and-minimize
- Coercion by Member Template
- Computational Constructor
- Concrete Data Type
- Construct On First Use
- Construction Tracker
- Copy-and-swap
- Copy-on-write
- Intrusive reference counting (Counted Body)
- Covariant Return Types TODO
- Curiously Recurring Template Pattern (CRTP)
- Empty Base Optimization (EBO)
- enable-if
- Erase-Remove
- Execute-Around Pointer
- Exploding Return Type TODO
- Export Guard Macro TODO
- Expression-template
- Fake Vtable TODO
- Fast Pimpl TODO
- Final Class
- Free Function Allocators
- Function Object TODO
- Generic Container Idioms
- Hierarchy Generation TODO
- Implicit conversions TODO
- Include Guard Macro
- Inline Guard Macro
- Inner Class
- Int-To-Type
- Interface Class
- Iterator Pair
- Making New Friends
- Metafunction
- Move Constructor
- Multi-statement Macro
- Member Detector
- Named Constructor
- Named External Argument TODO
- Named Loop (labeled loop)
- Named Parameter
- Named Template Parameters TODO
- Nifty Counter (Schwarz Counter)
- Non-copyable Mixin
- Non-member Non-friend Function TODO
- Non-throwing swap
- Non-Virtual Interface (NVI, Public Overloaded Non-Virtuals Call Protected Non-Overloaded Virtuals)
- nullptr
- Object Generator
- Object Template TODO
- Parameterized Base Class (Parameterized Inheritance)
- Pimpl (Handle Body, Compilation Firewall, Cheshire Cat)
- Policy Clone (Metafunction wrapper)
- Policy-based Design TODO
- Polymorphic Exception
- Polymorphic Value Types TODO
- Recursive Type Composition TODO
- Requiring or Prohibiting Heap-based Objects
- Resource Acquisition Is Initialization (RAII, Execute-Around Object, Scoped Locking)
- Resource Return
- Return Type Resolver
- Runtime Static Initialization Order Idioms
- Safe bool
- Scope Guard
- Substitution Failure Is Not An Error (SFINAE)
- Shortening Long Template Names TODO
- Shrink-to-fit
- Small Object Optimization TODO
- Smart Pointer
- Storage Class Tracker TODO
- Tag Dispatching TODO
- Temporary Base Class
- Temporary Proxy
- The result_of technique TODO
- Thin Template
- Traits TODO
- Type Erasure
- Type Generator (Templated Typedef)
- Type Safe Enum
- Type Selection
- Virtual Constructor
- Virtual Friend Function
Advanced idioms[edit]
These are some more advanced C++ idioms.
- Envelope Letter TODO
Deprecated idioms[edit]
Haskell
https://zh.m.wikibooks.org/wiki/Haskell
Rust
-
Rust patterns ref
-
TODO stability for extensibility
-
TODO trait to separate visibility of methods from visibility of data (https://github.com/sfackler/rust-postgres/blob/master/src/lib.rs#L1400)
-
TODO leak amplification (“Vec::drain sets the Vec’s len to 0 prematurely so that mem::forgetting Drain “only” mem::forgets more stuff. instead of exposing uninitialized memory or having to update the len on every iteration”)
-
TODO interior mutability - UnsafeCell, Cell, RefCell
-
TODO iterators (to safely avoid bounds checks)
-
TODO closures and lifetimes (coupling to lifetime)
-
TODO platform-specific sub-modules (https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md#platform-specific-opt-in)
-
Entry API (Currently just a boilerplate)
-
TODO extension traits
-
TODO destructor bombs (ensure linear typing dynamically, e.g., https://github.com/Munksgaard/session-types/commit/0f25ccb7c3bc9f65fa8eaf538233e8fe344a189a)
-
TODO convertible to Foo trait for more generic generics (e.g., http://static.rust-lang.org/doc/master/std/fs/struct.File.html#method.open)
-
Late bound bounds (Currently just a boilerplate)
-
TODO ‘shadow’ borrowed version of struct - e.g., double buffering, Niko’s parser generator
-
TODO composition of structs to please the borrow checker
-
TODO
Error
traits andResult
forwarding -
TODO graphs
-
Anti-patterns
- TODO thread + catch_panic for exceptions
- TODO Clone to satisfy the borrow checker
- Deref polymorphism
- TODO Matching all fields of a struct (back compat)
- TODO wildcard matches
- TODO taking an enum rather than having multiple functions
- TODO
unwrap()
ing everyResult
instead of forwarding it #[deny(warnings)\]
Architecture pattern
Sub-domain area | Architecture pattern | Software design patterns | Solution patterns | Related patterns |
---|---|---|---|---|
Data integration/SOA | ETL (data extraction transformation and loading) | Change data captureNear real-time ETLBatch ETLData discovery | Error handlingJob schedulingData validationSlowly changing dimensions load | EAIMaster data hubOperational data store (ODS)Data martData warehouse |
MFT | ||||
EAI/ESB | Publish/subscribeRequest/replyMessage exchange patterns | One-waySynchronous request/responseBasic callbackClaim check | SOA | |
Data architecture | Transaction data stores (TDS/OLTP)Master data storeOperational data storeData martData warehouse | Custom applications databasesPackaged application databases | ETLEAISOA | |
Analytics and business intelligence | Transactional reportingOperational analyticsBusiness analyticsPredictive analyticsPrescriptive analyticsStreaming analyticsData science and advanced analyticsNLP | Transactional reporting data accessOperational reporting data accessAnalytical reporting data accessAnalytical dashboard data accessOperational dashboard data accessData mining | Real-time dashboardsIn-memory analyticsStatistical analysisPredictive analytics | ETLEAITDSOperational data storeData mart |
Master data management | Master data hub | Master data replicationMaster data servicesMaster data synchronization | Change data captureEAISTD | |
Data modeling | Dimensional data modelingE-R data modeling | Modeling standardsNaming conventions | ||
Artificial intelligence | Decision managementSpeech recognitionText analytics and NLPNatural language generationClassic machine learningDeep learningRobotic process automationImage and video analysis |
Some additional examples of architectural patterns:
- Blackboard system
- Broker pattern
- Event-driven architecture
- Implicit invocation
- Layers
- Hexagonal architecture
- Microservices
- Action-domain-responder, Model–view–controller, Presentation-abstraction-control, Model-view-presenter, and Model-view-viewmodel
- Entity–component–system
- Entity-control-boundary
- Multitier architecture (often three-tier or n-tier)
- Naked objects
- Operational data store (ODS)
- Peer-to-peer
- Pipe and filter architecture
- Service-oriented architecture
- Space-based architecture
- Distributed hash table
https://en.wikipedia.org/wiki/Enterprise_architecture_framework
Distributed design patterns
- MapReduce
- Bulk synchronous parallel
- Remote Session[1]
- Event-driven architecture
- https://en.wikipedia.org/wiki/Security_pattern
- https://en.wikipedia.org/wiki/Distributed_object_communication
List of software development philosophies
Software development philosophies[edit]
Large-scale programming styles:
- Behavior-driven development
- Design-driven development
- Domain-driven design
- Secure by design
- Test-driven development
Specification-related paradigms:
Comprehensive systems:
- Agile software development
- Lightweight methodology
- Kanban (development)
- Cowboy coding (a non-system)
Rules of thumb:
- KISS principle
- Minimalism (computing)
- Open–closed principle
- Release early, release often
- Rule of least power
- There’s more than one way to do it
- Unix philosophy
- Worse is better
- You aren’t gonna need it (YAGNI)
- Don’t repeat yourself (DRY)
- SOLID (object-oriented design)
- Single source of truth (SSOT)
- Single version of the truth (SVOT)
Other:
- The Cathedral and the Bazaar - book comparing top-down vs. bottom-up open-source software
Programming paradigms[edit]
- Agent-oriented programming
- Aspect-oriented programming (AOP)
- Component-based software engineering
- Functional programming (FP)
- Modular programming
- Object-oriented programming (OOP)
- Reactive programming
Software development methodologies[edit]
- Agile Unified Process (AUP)
- Constructionist design methodology (CDM)
- Dynamic systems development method (DSDM)
- Extreme programming (XP)
- Iterative and incremental development
- Kanban
- Lean software development
- Open Unified Process
- Pair programming
- Rapid application development (RAD)
- Rational Unified Process (RUP)
- Scrum
- Structured systems analysis and design method (SSADM)
- Unified Process (UP)
Software development processes[edit]
- Active-Admin-driven development (AADD)
- Behavior-driven development (BDD)
- Bug-driven development (BgDD)
- Configuration-driven development (CDD)
- Design-driven development (D3)
- Domain-driven design (DDD)
- Feature-driven development (FDD)
- Test-driven development (TDD)
- User-centered design (UCD)
- Value-driven design (VDD)
Code_refactoring
https://en.wikipedia.org/wiki/Code_refactoring
软件开发过程
https://en.wikipedia.org/wiki/Software_development_process