Thursday, May 31, 2012

GIST NOTES 13 - Design Patterns


GIST NOTES 13 - Design Patterns

[DISCLAIMER: This is solely for non-commercial use. I don't claim ownership of this content. This is a crux of all my readings studies and analysis. Some of them are excerpts from famous books on  the subject. Some of them are my contemplation upon experiments with direct hand coded code samples using IDE or notepad.


I've created this mainly to reduce an entire book into few pages of critical content that we should never forget. Even after years, you don't need to read the entire book again to get back its philosophy. I hope these notes will help you to replay the entire book in your mind once again.]


OO Principles
-------------
-separate or encapsulate what changes frequently
-program to type/interface not the implementation
-Favor composition over inheritance
-Strive for loosely coupled designs between objects that interact
-Classes should be open for extension, but closed for modification.
-Dependency Inversion Principle:Depend upon abstractions. Do not depend upon concrete classes.
[[In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling where conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are inverted (i.e. reversed) for the purpose of rendering high-level modules independent of the low-level module implementation details. The principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.
]]
-Principle of Least Knowledge: talk only to your immediate friends.
-The Hollywood Principle: Don’t call us, we’ll call you.
-Single Responsibility Principle: A class should have only one reason to change.

Strategy Pattern --> (Pluggable Discovery Modules)

defines a family of algorithms,
encapsulates each one, and makes them
interchangeable. Strategy lets the algorithm
vary independently from clients that use it.

The Observer Pattern --> (Swing Event Listeners)

defines a one-to-many
dependency between objects so that when one
object changes state, all of its dependents are
notified and updated automatically.

-java.util.Observable is a class; Observer is an interface
If you look at the Observable API, the setChanged() method is protected. So what? Well,
this means you can’t call setChanged() unless you’ve subclassed Observable. This means
you can’t even create an instance of the Observable class and compose it with your own
objects, you have to subclass. The design violates a second design principle here…favor
composition over inheritance.

ß Swing makes heavy use of the
Observer Pattern, as do many
GUI frameworks.
ß You’ll also find the pattern in
many other places, including
JavaBeans and RMI.

Many of the patterns give us
time tested designs that protect your
code from being modified by supplying
a means of extension. In this chapter
you’ll see a good example of using the
Decorator pattern to follow the Open-
Closed principle.

The Decorator Pattern --> (Java IO Package)

attaches additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for extending functionality.

Decorator pattern makes the addon components of a main component as same type as main component and also these addons
can wrap the main component or another addon since they all extend from same supertype. Such wrapper addons
are called decorator classes. So decorators make adding addons to main component in any combination, easier.

Main classes and abstract decorator extend from supertype. Addon components extend from decorator.

Decorators have the same supertype as the objects they decorate.

But now that you know the Decorator Pattern, the I/O classes should make more sense
since the java.io package is largely based on Decorator.

FileInputStream and FilterInputStream extend from InputStrem.

FileInputStream is the subject which is decorated. FilterInputStream is the
abstract Decorator class from which concrete decorators like BufferedInputStream
and LineNumberInputStream extend.

But Java I/O also points out one of the downsides of the Decorator Pattern:
designs using this pattern often result in a large number of small classes
that can be overwhelming to a developer trying to use the Decorator-based
API.

Factory Pattern --> (Pluggable PortModules in a Switch EMS)

Simple Factory is not a Pattern. It is a programming idiom.

The Factory Method Pattern -->

defines an interface for creating an object, but lets subclasses decide which
class to instantiate. Factory Method lets a class defer
instantiation to subclasses.

The Abstract Factory Pattern -->

provides an interface for creating families of related or dependent objects
without specifying their concrete classes.

Factory Method - creates objects through inheritance
Abstract Factory - creates objects through object composition

The Singleton Pattern --> (Discovery Engine/Console object EMS/NMS)

ensures a class has only one instance, and provides a global point of access to it.

Double-checked locking doesn’t work in Java 1.4 or earlier!

Unfortunately, in Java version 1.4 and earlier, many
JVMs contain implementations of the volatile keyword
that allow improper synchronization for double-checked
locking. If you must use a JVM other than Java 5,
consider other methods of implementing your Singleton.

For each solution, describe its applicability to the problem of fixing the Chocolate
Boiler code:
Sharpen your pencil
Synchronize the getInstance() method:
Use eager instantiation:
Double-checked locking:

Prior to Java 1.2, a bug in the garbage collector allowed Singletons
to be prematurely collected if there was no global reference to them. In other
words, you could create a Singleton and if the only reference to the Singleton
was in the Singleton itself, it would be collected and destroyed by the garbage
collector.

One problem with subclassing
Singleton is that the constructor is
private. You can’t extend a class with
a private constructor.

intent of the pattern: to
ensure only one instance of a class
exists and to provide global access. A
global variable can provide the latter,
but not the former.

Be careful if you are using
multiple class loaders; this
could defeat the Singleton
implementation and result in
multiple instances.

If you are using a JVM earlier
than 1.2, you’ll need to create a
registry of Singletons to defeat
the garbage collector.

<1.2 garbage collector issue
<1.4 volatile allowed improper synchronization

public class Singleton {
*private* *volatile* static Singleton uniqueInstance;
*private* Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null**) {
synchronized (Singleton.class**) {
if (uniqueInstance == null**) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}

}

Need for volatile - since we are moving from method level sync to block level sync, the threads would keep separate copy of static variables in their stack instead of referring from heap. To avoid this, we make the variable involved as volatile. Or use a local variable inside the method to read/write uniqueInstance variable

Command Pattern -->

The Command Pattern encapsulates a request as an
object, thereby letting you parameterize other objects
with different requests, queue or log requests, and support
undoable operations.

The Meta Command Pattern allows you to create
macros of commands so that you can execute multiple commands
at once.

Adapter Pattern -->

The Adapter Pattern converts the interface of a class
into another interface the clients expect. Adapter lets
classes work together that couldn’t otherwise because of
incompatible interfaces.

There are actually two kinds of adapters: object adapters and class adapters.

This chapter has covered object adapters and the class diagram on the previous page is a
diagram of an object adapter.
So what’s a class adapter and why haven’t we told you about it? Because you need
multiple inheritance to implement it, which isn’t possible in Java. But, that doesn’t
mean you might not encounter a need for class adapters down the road when using
your favorite multiple inheritance language!

Object adapters and class adapters use two different means of
adapting the adaptee (composition versus inheritance).

Facade Pattern -->

We’re going to look at a pattern now that alters an interface, but for a
different reason: to simplify the interface. It’s aptly named the Facade
Pattern because this pattern hides all the complexity of one or more
classes behind a clean, well-lit facade.

Decorator -
Doesn’t alter the interface, but
adds responsibility

Adapter -
Converts one interface to
another

Facade -
Makes an interface simpler

with the Facade Pattern you can take a complex
subsystem and make it easier to use by implementing a Facade class that
provides one but more-reasonable interface.

difference between the Adapter Pattern and the
Facade Pattern is that the adapter wraps
one class and the facade may represent
many classes?
A: No! Remember, the Adapter Pattern
changes the interface of one or more
classes into one interface that a client is
expecting. While most textbook examples
show the adapter adapting one class, you
may need to adapt many classes to provide
the interface a client is coded to. Likewise,
a Facade may provide a simplified interface
to a single class with a very complex
interface.
The difference between the two is not in
terms of how many classes they “wrap,” it
is in their intent. The intent of the Adapter
Pattern is to alter an interface so that it
matches one a client is expecting. The
intent of the Facade Pattern is to provide a
simplified interface to a subsystem.

A facade not only simplifies an interface, it
decouples a client from a subsystem of components.

The Facade Pattern provides a unified interface to a
set of interfaces in a subsytem. Facade defines a higherlevel
interface that makes the subsystem easier to use.

Principle of Least Knowledge - Law of Demeter
talk only to your immediate friends.

Are there any disadvantages
to applying the Principle of Least
Knowledge?
A: Yes; while the principle reduces
the dependencies between objects and
studies have shown this reduces software
maintenance, it is also the case that
applying this principle results in more
“wrapper” classes being written to handle
method calls to other components. This
can result in increased complexity and
development time as well as decreased
runtime performance.

Adapter Pattern - interface is dictated by Clients
Facade Pattern - no one dictate the interface; it is just a simplification of a complex subsystem

Template Method Pattern(Hollywood Principle) --> (Swing paint() and Arrays/Collections.sort())

The Template Method defines the steps of an algorithm and allows
subclasses to provide the implementation for one or more steps.

The Template Method Pattern defines the skeleton
of an algorithm in a method, deferring some steps to
subclasses. Template Method lets subclasses redefine
certain steps of an algorithm without changing the
algorithm’s structure.

Use abstract methods when your subclass MUST provide an implementation
of the method or step in the algorithm. Use hooks when that part of the algorithm
is optional. With hooks, a subclass may choose to implement that hook, but it doesn’t
have to.

Another use is to give the subclass a chance to react to some step in the
template method that is about to happen, or just happened.

abstract method - forces the subclasses to implement a step in the algorithm
hooks - provide optional steps for subclasses

The Hollywood Principle: Don’t call us, we’ll call you.

The Hollywood principle gives us a way to prevent
“dependency rot.” Dependency rot happens when you have
high-level components depending on low-level components
depending on high-level components depending on sideways
components depending on low-level components, and so on.
When rot sets in, no one can easily understand the way a
system is designed.

the high-level components give the low-level
components a “don’t call us, we’ll call you” treatment.

when we design with the Template Method Pattern, we’re telling subclasses, “don’t call us, we’ll call
you.”

Template Method

Subclasses decide how to implement steps in an algorithm

Strategy

*Encapsulate* interchangeable behaviors and use *delegation* to decide which behavior to use

Factory Method (about creation of objects in the subclasses)

Subclasses decide which concrete classes to create

you’re going to have to implement this compareTo()
method; by doing that you’ll give the Arrays class
what it needs to complete the algorithm and sort - Arrays util class sort()
method uses Template patttern but without inheritance.

The designers of the Arrays sort() method had a few constraints. In general, you can’t
subclass a Java array and they wanted the sort to be used on all arrays (and each array
is a different class). So they defined a static method and deferred the comparison part of the algorithm to the items being sorted. So, while it’s not a textbook template
method, this implementation is still in the spirit of the Template Method Pattern.

But remember, in Strategy pattern, the class that you compose
with implements the entire algorithm. The algorithm that Arrays implements for sort
is incomplete; it needs a class to fill in the missing compareTo() method. So, in that
way, it’s more like Template Method.

Are there other examples of template methods in the Java API?
A: Yes, you’ll find them in a few places. For example, java.io has a read()
method in InputStream that subclasses must implement and is used by the template
method read(byte b[], int off, int len).

If you haven’t encountered JFrame, it’s the most basic Swing container and inherits
a paint() method. By default, paint() does nothing because it’s a hook! By overriding
paint(), you can insert yourself into JFrame’s algorithm for displaying its area of the
screen and have your own graphic output incorporated into the JFrame.

Hook method is a missing step in the template method pattern algorithm which is deferred to clients to be implemented later if they want.

We’re extending JFrame, which contains a method update() that controls the
algorithm for updating the screen. We can hook into that algorithm by
overriding the paint() hook method.

The init() hook allows the applet to do whatever it wants to initialize the applet the first time.

repaint() is a concrete method in the Applet class that lets upper-level components know
the applet needs to be redrawn.

And many other methods in Applet class are hooks.

To prevent subclasses from changing the algorithm in the
template method, declare the template method as final.

The Strategy and Template Method Patterns both
encapsulate algorithms, one by inheritance and one by composition.

The Factory Method is a specialization of Template Method.

Iterator Pattern ===> (Java Collections)

The Iterator Pattern provides a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.

Iterator Pattern places the task of traversal on the iterator
object, not on the aggregate, which simplifies the
aggregate interface and implementation, and places
the responsibility where it should be.

Q: I’ve heard about “internal” iterators and “external” iterators. What
are they? Which kind did we implement in the example?
A: We implemented an external iterator, which means that the client controls the
iteration by calling next() to get the next element. An internal iterator is controlled
by the iterator itself. In that case, because it’s the iterator that’s stepping through the
elements, you have to tell the iterator what to do with those elements as it goes through
them. That means you need a way to pass an operation to an iterator. Internal iterators
are less flexible than external iterators because the client doesn’t have control of
the iteration.

Java’s Collection Framework ListIterator can go backwards as well as forwards
It is supported by any Collection that implements the List interface.

A class should have only one reason to change.

Every responsibility of a class is an area of potential change. More than one
responsibility means more than one area of change.

We say that a module or class has high cohesion when it is designed around a set of
related functions, and we say it has low cohesion when it is designed around a
set of unrelated functions.

Composite Pattern ===>

The Composite Pattern allows you to compose objects into tree structures to
represent part-whole hierarchies. Composite lets clients treat individual objects and
compositions of objects uniformly.

Composite is the pattern to use when you have collections of objects with
whole-part(container within container) relationships and you want to be
able to treat those objects uniformly.

HeadFirst: Tell us a little more about how these composite and leaf objects are structured.

Composite: Usually it’s a tree structure, some kind of hierarchy. The root
is the top level composite, and all its children are either composites or leaf nodes.

Caching: Sometimes, if the composite structure is complex or expensive to traverse,
it’s helpful to implement caching of the composite nodes. For instance, if
you are constantly traversing a composite and all its children to compute
some result, you could implement a cache that stores the result temporarily to save traversals.

What do you consider your greatest strength?
Composite: I think I’d definitely have to say simplifying life
for my clients. My clients don’t have to worry about whether
they’re dealing with a composite object or a leaf object, so they
don’t have to write if statements everywhere to make sure they’re
calling the right methods on the right objects. Often, they can make
one method call and execute an operation over an entire structure.

An Iterator takes the job of iterating over an aggregate and encapsulates
it in another object.

The Composite Pattern allows clients to treat composites and individual objects uniformly.

There are many design tradeoffs in implementing Composite. You need
to balance transparency and safety with your needs.(between uniformity
of and unwanted method implementation by both leaf node and composite node.)

The State Pattern ===>

Allows an object to alter its behavior when its internal state
changes. The object will appear to change its class.

The State and Strategy Patterns have the same class diagram, but they differ in
intent.

Strategy Pattern - allows client to change its behavior by choosing another object(object composition); also there is no inherent sequence among different behaviors chosen by the client.

State Pattern - allows the Context class to change its behavior by choosing a different state object everytime. But here, the sequence of states the Context class goes through is determined already(though it can have multiple sequences). Either the Context class or the state object can change the state to another state object.

Context objects change state over time according to some well defined state
transitions. In other words, changing behavior is built in to its scheme – it’s how I work!

Using the State Pattern will typically result in a greater number of classes in your
design.

The Proxy Pattern ===>

Provides a surrogate or placeholder for another object to control access to it.

Use the Proxy Pattern to create a representative object that controls access
to another object, which may be remote, expensive to create or in need of securing.

ß As we know, a remote proxy controls access to a remote object.
ß A virtual proxy controls access to a resource that is expensive to create.
ß A protection proxy controls access to a resource based on access rights.

Sometimes Proxy and Decorator look very similar, but their purposes are
different: a decorator adds behavior to a class, while a proxy controls access
to it.

a specialized form of a Virtual Proxy called a Caching Proxy. A caching proxy
maintains a cache of previously created objects and when a request is made it
returns cached object, if possible.

Both Proxy and Adapter sit in front of other objects and forward requests to them. Remember that Adapter changes the interface of the objects it adapts, while the Proxy
implements the same interface.

A Protection Proxy may allow or disallow a client access to particular methods
in an object based on the role of the client. In this way a Protection Proxy
may only provide a partial interface to a client, which is quite similar to some
Adapters.

Of course I sometimes create objects, how do you think a virtual proxy gets its subject!

decorators only add window dressing; they never get to instantiate anything. like just a dumb proxy!

Java’s got its own proxy support right in the java.lang.reflect package. With this package, Java lets you create a proxy class on the fly that implements one or more interfaces and forwards method invocations to a class that you specify. Because the actual proxy class is created at runtime, we refer to this Java technology as a dynamic proxy.

Because Java creates the Proxy class for you, you need a way to tell the Proxy class what to do. You can’t put that code into the Proxy class like we did before, because you’re not implementing one directly. So, if you can’t put this code in the Proxy class, where do you put it? In an InvocationHaner.

The job of the InvocationHandler is to respond to any method calls on the proxy. Think of the InvocationHandler as the object the Proxy asks to do all the real work after it’s received the method calls.

What’s a Protection Proxy? It’s a proxy that controls access to an object based on access rights.

InvocationHandlers implement the behavior of the proxy

PersonBean getOwnerProxy(PersonBean person) {
return (PersonBean) Proxy.newProxyInstance(
person.getClass().getClassLoader(),
person.getClass().getInterfaces(),
new OwnerInvocationHandler(person));
}

The Proxy class has a static method called isProxyClass(). Calling this method with a class will return true if the class is a dynamic proxy class. Other than that, the proxy class will act like any other class that implements a particular set of interfaces.

Q: Are there any restrictions on the types of interfaces I can pass into newProxyInstance()?

A: Yes, there are a few. First, it is worth pointing out that we always
pass newProxyInstance() an array of interfaces – only interfaces are allowed, no classes. The major restrictions are that all non-public interfaces need to be from the same package. You also can’t have interfaces with clashing method names (that is, two interfaces with a method with the same signature). There are a few other minor
nuances as well, so at some point you should take a look at the fine print on dynamic proxies in the javadoc.

Q: I heard that in Java 5, I don’t even need to generate stubs anymore either. Is that true?

A: It sure is. In Java 5, RMI and Dynamic Proxy got together and now stubs are generated dynamically using Dynamic Proxy. The remote object’s stub is a java.lang.reflect.Proxy instance (with an invocation handler) that is automatically generated to handle all
the details of getting the local method calls by the client to the remote object.
So, now you don’t have to use rmic at all; everything you need to get a client talking to a remote object is handled for you behind the scenes.

Facade -Wraps a bunch of objects to simplify their interface

Decorator -Wraps another object and provides additional behavior for it

Proxy -Wraps another object to control access to it

Adapter -Wraps another object and provides a different interface to it

Complexity Hiding Proxy hides the complexity of and controls access to a complex set of classes. This is sometimes called the Facade Proxy for obvious reasons. The Complexity Hiding Proxy differs from the Facade Pattern in that the proxy controls access, while the Facade Pattern just provides an alternative interface.

Copy-On-Write Proxy controls the copying of an object by deferring the copying of an
object until it is required by a client. This is a variant of the Virtual Proxy.

Habitat: seen in the vicinity of the Java 5’s CopyOnWriteArrayList.

---

Compound Pattern ===>

A compound pattern combines two or more patterns into a solution that solves a recurring or general problem.

====> MVC

================================
Q: Does the controller ever become an observer of the model?
A: Sure. In some designs the controller registers with the model and is notified
of changes. This can be the case when something in the model directly affects the
user interface controls. For instance, certain states in the model may dictate that some
interface items be enabled or disabled. If so, it is really controller’s job to ask the view to update its display accordingly.

Q: All the controller does is take user input from the view and send it to the
model, correct? Why have it at all if that is all it does? Why not just have the code
in the view itself? In most cases isn’t the controller just calling a method on the
model?
A: The controller does more than just “send it to the model”, the controller is
responsible for interpreting the input and manipulating the model based on that input.
But your real question is probably “why can’t I just do that in the view code?”
You could; however, you don’t want to for two reasons: First, you’ll complicate
your view code because it now has two responsibilities: managing the user interface
and dealing with logic of how to control the model. Second, you’re tightly coupling your
view to the model. If you want to reuse the view with another model, forget it. The
controller separates the logic of control from the view and decouples the view from the
model. By keeping the view and controller loosely coupled, you are building a more
flexible and extensible design, one that can more easily accommodate changes down the
road.

Patterns involved in MVC
------------------------
As you might have guessed the model uses [Observer] to keep the views and controllers updated on the latest state changes. The view and the controller, on the other hand, implement the [Strategy Pattern]. The controller is the behavior of the view, and it can be easily exchanged with another controller if you want different behavior. The view itself also uses a pattern internally to manage the windows, buttons and other components of the display: the [Composite Pattern].

a pattern you’ll often see hanging around the MVC trio: the Adapter Pattern.

adapt the HeartModel to a BeatModel. If we don’t, the view won’t be able to work with the model, because the view only knows how to getBPM(), and the equivalent heart model method is getHeartRate().

Model 2 Pattern ===>

It wasn’t long after the Web was spun that developers started adapting the MVC to fit the browser/server model. The prevailing adaptation is known simply as “Model 2” and uses a combination of servlet and JSP technology to achieve the same separation of model, view and controller that we see in conventional GUIs.

Design Patterns and Model 2:

After implementing the DJ Control for the Web using Model 2, you might be wondering where the patterns went. We have a view created in HTML from a JSP but the view is no longer a listener of the model. We have a controller that’s a servlet that receives HTTP requests, but are we still using the Strategy Pattern? And what about Composite? We have a view that is made from HTML and displayed in a web browser. Is that still the Composite Pattern?

Model 2 is an adaptation of MVC to the Web Even though Model 2 doesn’t look exactly like “textbook” MVC, all the parts are still there; they’ve just been adapted to reflect the idiosyncrasies of the web browser model. Let’s take another look...

Q: Does the controller ever implement any application logic?
A: No, the controller implements behavior for the view. It is the smarts that translates the actions from the view to actions on the model.

The model takes those actions and implements the application logic to decide what to do in response to those actions.

Q: I’ve seen descriptions of the MVC where the controller is described as a
“mediator” between the view and the model. Is the controller implementing the
Mediator Pattern?
A: We haven’t covered the Mediator Pattern (although you’ll find a summary of
the pattern in the appendix), so we won’t go into too much detail here, but the intent of
the mediator is to encapsulate how objects interact and promote loose coupling by
keeping two objects from referring to each other explicitly. So, to some degree, the
controller can be seen as a mediator, since the view never sets state directly on the
model, but rather always goes through the controller. Remember, however, that the
view does have a reference to the model to access its state. If the controller were truly a mediator, the view would have to go through the controller to get the state of the model as well.

Q: If I have more than one view, do I always need more than one controller?
A: Typically, you need one controller per view at runtime; however, the same
controller class can easily manage many views.

Q: The view is not supposed to manipulate the model, however I noticed
in your implementation that the view has full access to the methods that change
the model’s state. Is this dangerous?
A: You are correct; we gave the view full access to the model’s set of methods.
We did this to keep things simple, but there may be circumstances where you want to
give the view access to only part of your model’s API. There’s a great design pattern
that allows you to adapt an interface to only provide a subset. Can you think of it?

We have a new category! MVC and Model 2 are compound patterns

The Adapter Pattern can be used to adapt a new model to an existing view and controller.

The view uses the Composite Pattern to implement the user interface, which usually
consists of nested components like panels, frames and buttons.

Model 2 is an adaptation of MVC for web applications.

In Model 2, the controller is implemented as a servlet and JSP & HTML implement the
view.

A Pattern is a solution to a [recurring] problem in a context

The context is the situation in which the pattern applies. This should be a recurring situation. The problem refers to the goal you are trying to achieve in this
context, but it also refers to any constraints that occur in the context.
The solution is what you’re after: a general design that anyone can apply which resolves the goal and set of constraints.

Pattern = Recurring[Context + Goals and constraints + Solution]

Example: You have a collection of objects.
You need to step through the objects without exposing the collection’s
implementation. Encapsulate the iteration into a separate class.

“If you find yourself in a context with a problem that has a goal
that is affected by a set of constraints, then you can apply
a design that resolves the goal and constraints and leads to a
solution.”

The Design Pattern definition tells us that the problem consists of a
goal and a set of constraints. Patterns gurus have a term for these: they call them
forces.

Forces = Goals + Constraints

Only when a solution balances both sides of the force (the light side: your goal, and the dark side: the constraints) do we have a useful pattern.

classic GoF catalog; it contains 23 fundamental Design Patterns.

Frank: GoF?
Jim: Right, that stands for the Gang of Four. The Gang of Four are
the guys that put together the first patterns catalog.

Creational patterns involve object instantiation and all provide a way to decouple a client from the objects it needs to instantiate.

Creational: Singleton, Abstract Factory, Factory Method, Builder, Prototype

Any pattern that is a Behavioral Pattern is concerned with how
classes and objects interact and distribute responsibility.

Behavioral: Template Method, Iterator, Command, Observer, State, Strategy, Mediator, Visitor, Memento, Interpreter, Chain-of-responsibility

Structural patterns let you compose classes or objects into larger structures.

Structural: Proxy, Facade, Decorator, Composite, Adapter, Flyweight, Bridge

Class patterns describe how relationships between
classes are defined via inheritance. Relationships in
class patterns are established at compile time.

Class Pattterns: Template Method, Factory Method, Adapter, Interpreter
(if the word 'Method' comes in the name of the pattern, then, subclass methods are involved in the pattern)

Object patterns describe relationships between objects and are primarily
defined by composition. Relationships in object patterns are typically
created at runtime and are more dynamic and flexible.

Object Patterns: Composite , Decorator, Proxy, Strategy, Bridge, Flyweight, Abstract Factory, Singleton, Builder, Prototype, State, Mediator, Chain of responsibility, Observer, Facade, Command, Memento, Iterator, Visitor

Patterns can introduce complexity, and we never want
complexity where it is not needed. But patterns are powerful when used
where they are needed. As you already know, patterns are proven
design experience that can be used to avoid common mistakes. They’re
also a shared vocabulary for communicating our design to others.

Put simply, “the GoF,” which includes Erich Gamma, Richard
Helm, Ralph Johnson and John Vlissides, is the group of guys who
put together the first patterns catalog and in the process, started an
entire movement in the software field!

An Anti-Pattern tells you how to go from a problem to a BAD solution.

Think about it like this: if there is a recurring bad solution to a
common problem, then by documenting it we can prevent other
developers from making the same mistake. After all, avoiding bad
solutions can be just as valuable as finding good ones!

----------------------
Anti-Pattern  ===>
----------------------
Name: Golden Hammer
Problem: You need to choose technologies for
your development and you believe that exactly one
technology must dominate the architecture.
Context: You need to develop some new system
or piece of software that doesn’t fit well with the
technology that the development team is familiar with.
Forces:
• The development team is committed to the
technology they know.
• The development team is not familiar with
other technologies.
• Unfamiliar technologies are seen as risky.
• It is easy to plan and estimate for
development using the familiar technology.
Supposed Solution: Use the familiar technology
anyway. The technology is applied obsessively to
many problems, including places where it is clearly
inappropriate.
Refactored Solution: Expanding the knowledge of
developers through education, training, and book
study groups that expose developers to new solutions.
Examples:
Web companies keep using and maintaining their
internal homegrown caching systems when open
source alternatives are in use.
---------------------------


Bridge Pattern ===>

Bridge Benefits
ß Decouples an implementation so that it is not bound permanently to an interface.
ß Abstraction and implementation can be extended independently.
ß Changes to the concrete abstraction classes don’t affect the client.

Bridge Uses and Drawbacks

ß Useful in graphic and windowing systems that need to run over multiple platforms.
ß Useful any time you need to vary an interface and an implementation in different ways.
ß Increases complexity.

Bridge - allows to vary both implementation and abstraction

Builder Pattern ===>

Builder - when an object needs to be constructed differently each time, it can be abstracted into a builder class. Client deals with builder interface/supertype only

Chain of Responsibility Pattern ===>

Chain of Responsibility - when you want to give more than one object a chance to handle a request. Each object in the chain acts as a handler and has a successor object. If it
can handle the request, it does; otherwise, it forwards the request to its successor.

-Commonly used in windows systems to handle events like mouse clicks and keyboard events.
-Can be hard to observe the runtime characteristics and debug.

Flyweight Pattern(one real many virtual objects) ===>

(one object emulating the presence of many objects by maitaining all their states)

when one instance of a class can be used to provide many “virtual instances.”

What if, instead of having thousands of Tree objects, you
could redesign your system so that you’ve got only one
instance of Tree, and a client object that maintains the state
of ALL your trees? That’s the Flyweight!

All the state, for ALL of your virtual Tree objects, is stored in 2D-array in the client object.

Interpreter Pattern(language interpretation) ===> to build an interpreter for a language.

Interpreting a language through set of Expression concrete classes which are related via inheritance and composition.

Mediator Pattern(star topology) ===> to centralize complex communications and control between related objects.

Mediator sits in the middle of the star topology in order to decouple surrounding objects from each other but still allow them to communicate with each other through mediator.

The Memento ====> (Saving EMS Switch GUI state)

has two goals:

ß Saving the important state of a system’s key object.
ß Maintaining the key object’s encapsulation.

Client can do save and restore operation on a key object using this pattern.

Prototype Pattern ===>

when creating an instance of a given class is either expensive or
complicated.

The Prototype Pattern allows you to make new instances by
copying existing instances. A key aspect of this pattern is that the client code can
make new instances without knowing which specific class is
being instantiated.

Benefits
-------
ß Hides the complexities of making new instances from
the client.
ß Provides the option for the client to generate objects
whose type is not known.
ß In some circumstances, copying an object can be
more efficient than creating a new object.

Visitor Pattern ===>

 when you want to add capabilities to a composite of objects
and encapsulation is not important.

when new operation is needed to be performed, client asks the visitor to do it without changing the structure of the target composite object.

e.g. a datastructure presents all elements to the visitor and lets the visitor decide what to do with them

===========================x=========================

Reference: Head First

No comments:

Post a Comment