Strategy Pattern: define a family of algorithms, encapsulate each one, and make them interchangeable, which can reduce the number of classes and can reduce errors.
class Example {
public:
Example();
void setStrategy(Strategy* strategy_in);
private:
Strategy* strategy;
};
class Strategy {
//…
};
class Strategy1 : Strategy {
//…
};
- when algorithms of similar use have to be altered under different operating systems.
- when different characters will use different implementations of the same movements in a game.
- Have a family of algorithms to solve a problem and need to choose one of them easily.
Define skeleton (骨架) of an algorithm
Deferring (延迟) some steps to subclasses
Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure
- when the same algorithm only has a little changes to different tasks. it’s often used alongside with Strategy method.
- One algorithm is going to deal with data with different types.
- Provide a surrogate or placeholder for another object to control access to it.
Before and after providing access to the object, different tasks can be added for different purposes.
- when access to certain object is need to be protected or controlled. (for example, creating expensive objects only when needed; avoid unauthorized access to certain objects.)
- when additional functions are need to be added to original/existing objects. (for example, sending waiting messages to clients, do some extra work (like counting) when a certain object is called.)
- When you want different perform in different situation of a given class.
- you want to check whether the parameter is valid before send them into the given class.
- Proxy wraps one object to control it’s access; Adapter wraps one or more objects to adapt their interface to the user program
- Proxy does not change interface; Adapter may change interface
- Proxy often changes functionality; Adapter does not change functionality
- It encapsulates an action as an object, which can further be easily logged and even undone.
- use a command list to save all commands/several latest commands.
- when undo is called, execute all commands before the latest command on an empty canvas once again.
- when redo is called, execute the last command that has been omitted in the undo part on the canvas.