In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations.
In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
In object-oriented programming (OOP), a factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be “new”.
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes
代码例子
翻译上面门的例子。首先我们有了门 Door 的接口和一些实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
interfaceDoor{ publicfunctiongetDescription(); }
classWoodenDoorimplementsDoor{ publicfunctiongetDescription() { echo'I am a wooden door'; } }
classIronDoorimplementsDoor{ publicfunctiongetDescription() { echo'I am an iron door'; } }
The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
// Clone and modify what is required $cloned = clone$original; $cloned->setName('Dolly'); echo$cloned->getName(); // Dolly echo$cloned->getCategory(); // Mountain sheep
你也可以使用魔法方法 __clone 来改变克隆逻辑。
何时使用?
当一个对象需要跟已有的对象相似,或者当创造过程比起克隆来太昂贵时。
💍 单例模式
现实例子
一个国家同一时间只能有一个总统。当使命召唤的时候,这个总统要采取行动。这里的总统就是单例的。
白话
确保指定的类只生成一个对象。
维基百科
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.
The bridge pattern is a design pattern used in software engineering that is meant to “decouple an abstraction from its implementation so that the two can vary independently”
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.
In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
A proxy, in its most general form, is a class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked.
In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
比如,有三个支付方式 (A, B 和 C) 安装在你的账户里;每种方式都有不同额度。A 有 100 元, B 有 300 元,以及 C 有 1000 元,选择支付方式的顺序是 A 然后 B 然后 C。你要买一些价值 210 元的东西。使用责任链模式,首先账户 A 会被检查是否能够支付,如果是,支付会被执行而链子终止。如果否,请求会转移到账户 B,检查额度,如果是,链子终止,否则请求继续转移直到找到合适的执行者。这里 A,B 和 C 是链接里的环节,它们合起来就是责任链。
白话
它构造了一个对象的链。请求进入一端,然后从一个对象到另一个对象直到找到合适的执行者。
维基百科
In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.
In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
代码例子
首先我们有一个接收者,包含了每一个可执行的功能的实现
1 2 3 4 5 6 7 8 9 10
// Receiver classBulb{ publicfunctionturnOn() { echo"Bulb has been lit"; } publicfunctionturnOff() { echo"Darkness!"; } }
In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.
In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program’s running behavior.
// 输入一些东西 $editor->type('This is the first sentence.'); $editor->type('This is second.');
// 保存状态到:This is the first sentence. This is second. $saved = $editor->save();
// 输入些别的东西 $editor->type('And this is third.');
// 输出: Content before Saving echo$editor->getContent(); // This is the first sentence. This is second. And this is third.
// 恢复到上次保存状态 $editor->restore($saved);
$editor->getContent(); // This is the first sentence. This is second.
😎 观察者模式
现实例子
一个好的例子是求职者,他们订阅了一些工作发布网站,当有合适的工作机会时,他们会收到提醒。
白话
定义了一个对象间的依赖,这样无论何时一个对象改变了状态,其他所有依赖者会收到提醒。
维基百科
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to follow the open/closed principle.
classJumpimplementsAnimalOperation{ publicfunctionvisitMonkey(Monkey $monkey) { echo'Jumped 20 feet high! on to the tree!'; } publicfunctionvisitLion(Lion $lion) { echo'Jumped 7 feet! Back on the ground!'; } publicfunctionvisitDolphin(Dolphin $dolphin) { echo'Walked on water a little and disappeared'; } }
然后这样用
1 2 3 4 5 6 7 8 9 10
$jump = new Jump();
$monkey->accept($speak); // Ooh oo aa aa! $monkey->accept($jump); // Jumped 20 feet high! on to the tree!
$lion->accept($speak); // Roaaar! $lion->accept($jump); // Jumped 7 feet! Back on the ground!
$dolphin->accept($speak); // Tuut tutt tuutt! $dolphin->accept($jump); // Walked on water a little and disappeared
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables an algorithm’s behavior to be selected at runtime.
The state pattern is a behavioral software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, and implementing state transitions by invoking methods defined by the pattern’s superclass.
The state pattern can be interpreted as a strategy pattern which is able to switch the current strategy through invocations of methods defined in the pattern’s interface.
In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm’s structure.