| Start |
|---|
| Decorator Pattern Decorator pattern adds behavior to objects without affecting other objects of the same class. The decorator pattern is a useful alternative to creating sub-classes. Create a module for each decorator. This approach is more flexible than inheritance because you can mix and match responsibilities in more combinations. Additionally, because the transparency allows decorators to be nested recursively, it allows for an unlimited number of responsibilities. Assume the Pizza class has a cost method that returns 300: Represent pizza with an added layer of cheese burst and the cost goes up by 50. The simplest approach is to create a Next, we need to represent a large pizza that adds 100 to the cost of a normal pizza. We can represent this using a LargePizza subclass of Pizza. We could also have an ExtraLargePizza which adds a further cost of 15 to our LargePizza. If we were to consider that these pizza types could be served with cheese, we would need to add LargePizzaWithChese and ExtraLargePizzaWithCheese subclasses.we end up with a total of 6 classes. To simplify the approach, use modules to dynamically add behavior to Pizza class: Module + extend + super decorator:-> |
| Observer The observer pattern is a software design pattern in which an object (called Ruby provides a simple mechanism to implement the Observer design pattern. The module For this to work, the observable has to assert it has changed and notify the observers. Objects observing have to implement an Let's implement a small chat, where users can subscribe to users and when one of them write something, the subscribers get notified. Producing the following output: We've triggered the method The more subscribers we add the more the changes will propagate. |
| Singleton Ruby Standard Library has a Singleton module which implements the Singleton pattern. The first step in creating a Singleton class is to require and include the If you try to instantiate this class as you normally would a regular class, a To access the instance of this class, we need to use the Logger example In order to use Without Singleton include The above singleton implementations can also be done without the inclusion of the Singleton module. This can be achieved with the following: which is a shorthand notation for the following: However, keep in mind that the Singleton module is tested and optimized, therefore being the better option to implement your singleton with. |
| Proxy Proxy object is often used to ensure guarded access to another object, which internal business logic we don't want to pollute with safety requirements. Suppose we'd like to guarantee that only user of specific permissions can access resource. Proxy definition: (it ensure that only users which actually can see reservations will be able to consumer reservation_service) Models and ReservationService: Consumer service: Test:
Remarks |
Read Article
https://develop.horje.com/learn/1434/reference