Patterns

patterns

[TOC]

General Patterns

  1. active record
  2. mvc
  3. mvvm
  4. state machine
  5. reference couting
  6. COW(Copy On Write)
  7. iterator
  8. 組合子邏輯
  9. 柯里化(英語:Currying)
  10. λ演算
  11. monod
  12. Curiously recurring template pattern (CRTP)
  13. https://en.wikipedia.org/wiki/Double-chance_function
  14. SOLID设计原则
  15. https://en.wikipedia.org/wiki/GRASP_(object-oriented_design)

并發相關

  1. active object
  2. actor model
  3. blockingQueue
    1. take
    2. put
  4. ForkJoinPool

    1. execute
  5. future, promise, delay, deferred
  6. proactor
  7. reactor
  8. flow-graph
  9. https://en.wikipedia.org/wiki/Algorithmic_skeleton

GOF

  1. GoF: ref ref ref_cn ref
  2. 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

    1. Structural
      1. Adapter
      2. Bridge
      3. Composite
      4. Decorator
      5. Facade
      6. Flyweight
      7. Proxy
      8. 3.1Adapter
      9. 3.2Bridge
      10. 3.3Composite
      11. 3.4Decorator
      12. 3.5Facade
      13. 3.6Flyweight
      14. 3.7Proxy
      15. 3.8Curiously Recurring Template
      16. 3.9Interface-based Programming (IBP)
    2. Behavioral
      1. Chain of Responsibility
      2. Command
      3. Iterator
      4. Mediator
      5. Memento
      6. Observer
      7. Visitor
      8. Strategy
      9. State
      10. Template Method
      11. 4.1Chain of Responsibility
      12. 4.2Command
      13. 4.3Interpreter
      14. 4.4Iterator
      15. 4.5Mediator
      16. 4.6Memento
      17. 4.7Observer
      18. 4.8State
      19. 4.9Strategy
      20. 4.10Template Method
      21. 4.11Visitor
      22. 4.12Model-View-Controller (MVC)

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++

  1. Modern C++ patterns ref

    1. 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.
    2. Plain functions instead of factories, singletons etc.
    3. Inheritance not more than 1 layer deep and from mostly abstract base classes only (except for simple “helper” methods)
    4. Composition over inheritance
    5. 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
    6. 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的手段。函數指針會使抽象程度增加,但這是爲了封裝和維護性
    7. “Immutability as the default” is something I still struggle with, but try to adopt for future code I write
    8. If immutability is not an option, data structures where data is only added but never removed also helps
  2. Lazy evaluation

  3. Recursion, List Manipulation, and Lazy Evaluation

  4. 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

ref CN

  1. Address Of 75% developed as of 9 Oct 2011
  2. Algebraic Hierarchy 75% developed as of 12 June 2008
  3. Attach by Initialization 75% developed as of 22 Oct 2011
  4. Attorney-Client 75% developed as of 9 Oct 2011
  5. Barton-Nackman trick 75% developed as of 21 Feb 2011
  6. Base-from-Member 75% developed as of 6 August 2007
  7. Boost mutant 75% developed as of 9 May 2010
  8. Calling Virtuals During Initialization 75% developed as of 6 August 2007
  9. Capability Query 100% developed as of 21 Feb 2011
  10. Checked delete 75% developed as of 15 August 2007
  11. Clear-and-minimize 75% developed as of 10 August 2007
  12. Coercion by Member Template 100% developed as of 14 August 2007
  13. Computational Constructor 75% developed as of 9 Oct 2011
  14. Concrete Data Type 75% developed as of 17 March 2008
  15. Construct On First Use 75% developed as of 6 August 2007
  16. Construction Tracker 75% developed as of 6 August 2007
  17. Copy-and-swap 75% developed as of 10 August 2007
  18. Copy-on-write 100% developed as of 20 May 2009
  19. Intrusive reference counting (Counted Body) 75% developed as of 16 November 2007
  20. Covariant Return Types TODO
  21. Curiously Recurring Template Pattern (CRTP) 75% developed as of 6 August 2007
  22. Empty Base Optimization (EBO) 75% developed as of 9 Oct 2011
  23. enable-if 75% developed as of 21 Feb 2011
  24. Erase-Remove 75% developed as of 17 November 2007
  25. Execute-Around Pointer 75% developed as of 6 August 2007
  26. Exploding Return Type TODO
  27. Export Guard Macro TODO
  28. Expression-template 75% developed as of 6 August 2007
  29. Fake Vtable TODO
  30. Fast Pimpl 0% developed as of 6 August 2007 TODO
  31. Final Class 75% developed as of 10 May 2010
  32. Free Function Allocators75% developed as of 18 June 2014
  33. Function Object TODO
  34. Generic Container Idioms 75% developed as of 22 November 2007
  35. Hierarchy Generation TODO
  36. Implicit conversions TODO
  37. Include Guard Macro 75% developed as of 3 November 2007
  38. Inline Guard Macro 75% developed as of 3 November 2007
  39. Inner Class 75% developed as of 31 August 2007
  40. Int-To-Type 75% developed as of 21 September 2008
  41. Interface Class 75% developed as of 6 January 2008
  42. Iterator Pair 100% developed as of 28 October 2007
  43. Making New Friends 75% developed as of 5 January 2008
  44. Metafunction 75% developed as of 15 September 2008
  45. Move Constructor 100% developed as of 13 August 2007
  46. Multi-statement Macro 75% developed as of 16 February 2008
  47. Member Detector 75% developed as of 10 May 2010
  48. Named Constructor 75% developed as of 28 September 2008
  49. Named External Argument TODO
  50. Named Loop (labeled loop) 75% developed as of 9 May 2010
  51. Named Parameter 75% developed as of 11 May 2010
  52. Named Template Parameters TODO
  53. Nifty Counter (Schwarz Counter) 75% developed as of 6 August 2007
  54. Non-copyable Mixin 75% developed as of 6 August 2007
  55. Non-member Non-friend Function 0% developed as of 10 March 2008 TODO
  56. Non-throwing swap 75% developed as of 9 January 2008
  57. Non-Virtual Interface (NVI, Public Overloaded Non-Virtuals Call Protected Non-Overloaded Virtuals) 75% developed as of 12 June 2008
  58. nullptr 75% developed as of 3 November 2007
  59. Object Generator 75% developed as of 14 September 2008
  60. Object Template TODO
  61. Parameterized Base Class (Parameterized Inheritance) 75% developed as of 6 August 2007
  62. Pimpl (Handle Body, Compilation Firewall, Cheshire Cat) 0% developed as of 2nd March 2011
  63. Policy Clone (Metafunction wrapper) 100% developed as of 14 August 2007
  64. Policy-based Design TODO
  65. Polymorphic Exception 75% developed as of 28 September 2008
  66. Polymorphic Value Types 0% developed as of 24 June 2012 TODO
  67. Recursive Type Composition TODO
  68. Requiring or Prohibiting Heap-based Objects
  69. Resource Acquisition Is Initialization (RAII, Execute-Around Object, Scoped Locking) 100% developed as of 6 November 2007
  70. Resource Return 75% developed as of 3 November 2007
  71. Return Type Resolver 75% developed as of 10 May 2010
  72. Runtime Static Initialization Order Idioms 75% developed as of 6 August 2007
  73. Safe bool 75% developed as of 6 August 2007
  74. Scope Guard 100% developed as of 14 August 2007
  75. Substitution Failure Is Not An Error (SFINAE) 75% developed as of 12 May 2012
  76. Shortening Long Template Names TODO
  77. Shrink-to-fit 75% developed as of 10 August 2007
  78. Small Object Optimization TODO
  79. Smart Pointer 75% developed as of 17 November 2007
  80. Storage Class Tracker TODO
  81. Tag Dispatching 0% developed as of 21 October 2007 TODO
  82. Temporary Base Class 75% developed as of 6 August 2007
  83. Temporary Proxy 75% developed as of 6 August 2007
  84. The result_of technique TODO
  85. Thin Template 75% developed as of 6 August 2007
  86. Traits 0% developed as of 21 October 2007 TODO
  87. Type Erasure 75% developed as of 4 February 2015
  88. Type Generator (Templated Typedef) 75% developed as of 14 September 2008
  89. Type Safe Enum 75% developed as of 11 May 2010
  90. Type Selection 75% developed as of 9 May 2010
  91. Virtual Constructor 75% developed as of 17 March 2008
  92. Virtual Friend Function 75% developed as of 10 May 2010

Advanced idioms[edit]

These are some more advanced C++ idioms.

  1. Envelope Letter 75% developed as of 1 February 2008 TODO

Deprecated idioms[edit]

  1. Const auto_ptr 75% developed as of 15 August 2007

Haskell

https://zh.m.wikibooks.org/wiki/Haskell

Rust

  1. Rust patterns ref

    1. Constructor

    2. Concatenating strings with format!

    3. Privacy for extensibility

    4. TODO stability for extensibility

    5. TODO trait to separate visibility of methods from visibility of data (https://github.com/sfackler/rust-postgres/blob/master/src/lib.rs#L1400)

    6. Collections are smart pointers

    7. 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”)

    8. Finalisation in destructors

    9. TODO interior mutability - UnsafeCell, Cell, RefCell

    10. Iterating over an Option

    11. Default trait

    12. Pass variables to closure

    13. mem::replace(_) to avoid needless clones

    14. Temporary mutability

    15. Builder

    16. RAII guards

    17. Newtype

    18. TODO iterators (to safely avoid bounds checks)

    19. TODO closures and lifetimes (coupling to lifetime)

    20. TODO platform-specific sub-modules (https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md#platform-specific-opt-in)

    21. Entry API (Currently just a boilerplate)

    22. Visitor

    23. Fold

    24. Prefer small crates

    25. Contain unsafety in small modules

    26. TODO extension traits

    27. TODO destructor bombs (ensure linear typing dynamically, e.g., https://github.com/Munksgaard/session-types/commit/0f25ccb7c3bc9f65fa8eaf538233e8fe344a189a)

    28. 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)

    29. Late bound bounds (Currently just a boilerplate)

    30. TODO ‘shadow’ borrowed version of struct - e.g., double buffering, Niko’s parser generator

    31. TODO composition of structs to please the borrow checker

    32. TODO Error traits and Result forwarding

    33. TODO graphs

    34. Compose structs together for better borrowing

    35. FFI patterns

  2. Anti-patterns

    1. TODO thread + catch_panic for exceptions
    2. TODO Clone to satisfy the borrow checker
    3. Deref polymorphism
    4. TODO Matching all fields of a struct (back compat)
    5. TODO wildcard matches
    6. TODO taking an enum rather than having multiple functions
    7. TODO unwrap()ing every Result instead of forwarding it
    8. #[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:

https://en.wikipedia.org/wiki/Enterprise_architecture_framework

Distributed design patterns

List of software development philosophies

Software development philosophies[edit]

Large-scale programming styles:

Specification-related paradigms:

Comprehensive systems:

Rules of thumb:

Other:

Programming paradigms[edit]

Software development methodologies[edit]

Software development processes[edit]

Code_refactoring

https://en.wikipedia.org/wiki/Code_refactoring

软件开发过程

https://en.wikipedia.org/wiki/Software_development_process

Powered by Jekyll and Theme by solid

本站总访问量