Showing posts with label design patterns. Show all posts
Showing posts with label design patterns. Show all posts

Saturday, March 23, 2013

Disruptor Pattern



  • LMAX Disruptor

High Performance Inter-Thread Messaging Library
The Disruptor is a general-purpose mechanism for solving a difficult problem in concurrent programming.
It works in a different way to more conventional approaches, so you use it a little differently than you might be used to.
For example, applying the pattern to your system is not as simple as replacing all your queues with the magic ring buffer.
http://lmax-exchange.github.com/disruptor/

Wednesday, November 28, 2012

Refactoring › Composing Methods -Extract Method

  • You have a code fragment that can be grouped together.

Turn the fragment into a method whose name explains the purpose of the method.

Example: No Local Variables

before
 // print banner
    System.out.println ("**************************");
    System.out.println ("***** Customer Owes ******");
    System.out.println ("**************************");


after

printBanner();

void printBanner() {
    // print banner
    System.out.println ("**************************");
    System.out.println ("***** Customer Owes ******");
    System.out.println ("**************************");
}

http://sourcemaking.com/refactoring/extract-method



  • The Extract Method refactoring has the following limitations:


    Refactoring does not work with multiple output values in automatic mode. You have to change your code before applying the refactoring.
    Refactoring does not work for a code fragment which conditionally returns from the containing method and is not placed at the end of it.

before (eclipse)

  public class ExtractMethod1 {

public static void main(String[] args) {
method1();
}



 static void method1() {
   int a=1;
   int b=2;
   int c=a+b;
   int d=a+c;
}
}




after (eclipse)

public class ExtractMethod1 {

public static void main(String[] args) {

method1();
}



 static void method1() {
   getSum();
}



private static void getSum() {
int a=1;
int b=2;
int c=a+b;
int d=a+c;
}
}


In Eclipse you select the code fragment you want to refactor,right click,refactor and extract method


before (IntelliJ IDEA 11.1)

  public class ExtractMethod1 {

public static void main(String[] args) {
method1();
}



 static void method1() {
   int a=1;
   int b=2;
   int c=a+b;
   int d=a+c;
}
}


after (IntelliJ IDEA 11.1)

public class ExtractMethod1 {


public static void main(String[] args) {

method1();
}



 static void method1() {
   int a=1;
int b=2;
int c=add(a,b);
int d=add(a,c);
}


private static int add(int a,int b) {
return a+b;
}
}



before (IntelliJ IDEA 11.1)

ArrayList method2()
{
String[] strings={"a","b","c","d"};
ArrayList list=new ArrayList();

for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
return list;
}

}


after (IntelliJ IDEA 11.1)

private ArrayList add(String[] strings)
{
ArrayList list=new ArrayList();

for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
return list;
}


http://www.jetbrains.com/idea/webhelp/extract-method.html#h2example



  • Extract Method


The Extract Method refactoring allows you to select a block of code and convert it to a method. Eclipse automatically infers the method arguments and return types.
This is useful when a method is too big and you want to subdivide blocks of it into different methods. It is also useful if you have a piece of code that is reused across many methods. When you select one of those blocks of code and do a refactoring, Eclipse finds other occurrences of that block of code and replaces it with a call to the new method.

Listing 3. Before Extract Method refactoring

@Override
public Object get(Object key)
{
TimedKey timedKey = new TimedKey(System.currentTimeMillis(), key);
Object object = map.get(timedKey);

if (object != null)
{
/**
* if this was removed after the 'get' call by the worker thread
* put it back in
*/
map.put(timedKey, object);
return object;
}

return null;
}



Listing 4. After Before Extract Method refactoring

@Override
public Object get(Object key)
{
TimedKey timedKey = new TimedKey(System.currentTimeMillis(), key);
Object object = map.get(timedKey);

return putIfNotNull(timedKey, object);
}

private Object putIfNotNull(TimedKey timedKey, Object object)
{
if (object != null)
{
/**
* if this was removed after the 'get' call by the worker thread
* put it back in
*/
map.put(timedKey, object);
return object;
}

return null;
}
http://www.ibm.com/developerworks/opensource/library/os-eclipse-refactoring/index.html

Refactoring


Defining Refactoring
 
 
    Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.

The other usage of refactoring is the verb form
    Refactor (verb): to restructure software by applying a series of refactorings without changing its observable behavior.

“Is refactoring just cleaning up code?” In a way the answer is yes, but I think refactoring goes further because it provides a technique for cleaning up code in a more efficient and controlled manner

 the purpose of refactoring is to make the software easier to understand and modify.
 Only changes made to make the software easier to understand are refactorings
 Like refactoring, performance optimization does not usually change the behavior of a component (other than its speed); it only alters the internal structure
 the purpose is different. Performance optimization often makes code harder to understand, but you need to do it to get the performance you need.
 The software still carries out the same function that it did before

 When you use refactoring to develop software, you divide your time between two distinct activities: adding function and refactoring

 When you add function, you shouldn’t be changing existing code; you are just adding new capabilities. You can measure your progress by adding tests and getting the tests to work
 When you refactor, you make a point of not adding function; you only restructure the code. You don’t add any tests (unless you find a case you missed earlier)

 http://sourcemaking.com/refactoring/defining-refactoring




Why Should You Refactor?
The harder it is to see the design in the code, the harder it is to preserve it, and the more rapidly it decays. Regular refactoring helps code retain its shape.
By eliminating the duplicates, you ensure that the code says everything once and only once, which is the essence of good design.

Refactoring Makes Software Easier to Understand
Refactoring helps you to make your code more readable.
Ralph Johnson describes these early refactorings as wiping the dirt off a window so you can see beyond.
http://sourcemaking.com/refactoring/why-should-you-refactor


Refactoring Helps You Program Faster
When I talk about refactoring, people can easily see that it improves quality. Improving design, improving readability, reducing bugs, all these improve quality. But doesn’t all this reduce the speed of development?
the whole point of having a good design is to allow rapid development. Without a good design, you can progress quickly for a while, but soon the poor design starts to slow you down.
http://sourcemaking.com/refactoring/refactoring-helps-you-find-bugs


When Should You Refactor?
In my view refactoring is not an activity you set aside time to do. Refactoring is something you do all the time in little bursts

The Rule of Three
he first time you do something, you just do it.
The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway.
The third time you do something similar, you refactor.

Refactor When You Add Function
The most common time to refactor is when I want to add a new feature to some software
This code may have been written by someone else, or I may have written it
 Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent

 I look at the design and say to myself, “If only I’d designed the code this way, adding this feature would be easy.” In this case I don’t fret over my past misdeeds—I fix them by refactoring

 Refactor When You Need to Fix a Bug
 As I look at the code trying to understand it, I refactor to help improve my understanding.
 if you do get a bug report, it’s a sign you need refactoring, because the code was not clear enough for you to see there was a bug


Refactor As You Do a Code Review
Reviews help more experienced developers pass knowledge to less experienced people
My code may look clear to me but not to my team.
This idea of active code review is taken to its limit with the Extreme Programming [Beck, XP] practice of Pair Programming

Why Refactoring Works
Kent Beck

Programs have two kinds of value: what they can do for you today and what they can do for you tomorrow. Most times when we are programming, we are focused on what we want the program to do today. Whether we are fixing a bug or adding a feature, we are making today’s program more valuable by making it more capable

If you can get today’s work done today, but you do it in such a way that you can’t possibly get tomorrow’s work done tomorrow, then you lose.

http://sourcemaking.com/refactoring/when-should-you-refactor


Changing Interfaces
Something that is disturbing about refactoring is that many of the refactorings do change an interface. Something as simple as Rename Method is all about changing an interface. So what does this do to the treasured notion of encapsulation?



You should also use the deprecation facility in Java to mark the code as deprecated. That way your callers will know that something is up.
A good example of this process is the Java collection classes. The new ones present in Java 2 supersede the ones that were originally provided

When Shouldn’t You Refactor?
There are times when you should not refactor at all. The principle example is when you should rewrite from scratch instead. There are times when the existing code is such a mess that although you could refactor it, it would be easier to start from the beginning.

The other time you should avoid refactoring is when you are close to a deadline. At that point the productivity gain from refactoring would appear after the deadline and thus be too late

http://sourcemaking.com/refactoring/problems-with-refactoring

Wednesday, November 21, 2012

inheritance vs composition

About inheritance
In this article, I'll be talking about single inheritance through class extension, as in:

class Fruit {

    //...
}

class Apple extends Fruit {

    //...
}

In this simple example, class Apple is related to class Fruit by inheritance, because Apple extends Fruit. In this example, Fruit is the superclass and Apple is the subclass.



bout composition
By composition, I simply mean using instance variables that are references to other objects. For example:

class Fruit {

    //...
}

class Apple {

    private Fruit fruit = new Fruit();
    //...
}

In the example above, class Apple is related to class Fruit by composition, because Apple has an instance variable that holds a reference to a Fruit object. In this example, Apple is what I will call the front-end class and Fruit is what I will call the back-end class. In a composition relationship, the front-end class holds a reference in one of its instance variables to a back-end class.

The composition alternative
Given that the inheritance relationship makes it hard to change the interface of a superclass, it is worth looking at an alternative approach provided by composition. It turns out that when your goal is code reuse, composition provides an approach that yields easier-to-change cod


http://www.artima.com/designtechniques/compoinh.html

inheritance vs delegation java

  • inheritance vs  delegation java


Inheritance is used to create a hierarchical-type code structure that tries to keep as much “common” code near the top of the hierarchy.
In small, static systems, inheritance can be ok.
But large inheritance chains can also lead to hard-to-maintain code
design patterns that favor composition over inheritance for more info when to use inheritance and when not to.

Delegation is simply passing a duty off to someone/something else.
Delegation is alternative to inheritance.
Delegation means that you use an object of another class as an instance variable, and forward messages to the instance.


It is better than inheritance because it makes you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class
you can provide only the methods that really make sense.
Delegation can also a powerful design/reuse technique.
The primary advantage of delegation is run-time flexibility
the delegate can easily be changed at run-time.


the choice between delegation and inheritance is driven by external factors such as programming language support for multiple inheritance or design constraints requiring polymorphism.

Consider threads in Java. You can associate a class with a thread in one of two ways: either by extending (inheriting) directly from class Thread, or by implementing the Runnable interface and then delegating to a Thread object

Often the approach taken is based on the restriction in Java that a class can only extend one class (i.e., Java does not support multiple inheritance). If the class you want to associate with a thread already extends some other class in the design, then you would have to use delegation; otherwise, extending class Thread would usually be the simpler approach

http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html#ixzz2CqNmtYMM

Lazy initialization

  • Lazy initialization
In computer programming, lazy initialization is the 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.

In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas:

    using a factory method to get instances of a class (factory method pattern)
    storing the instances in a map, so you get the same instance the next time you ask for an instance with same parameter (Multiton pattern, similar to the singleton pattern)
    using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern).

http://en.wikipedia.org/wiki/Lazy_initialization#Java





  • Lazy initialization is a performance optimization.

if the hashCode value for an object might not actually be needed by its caller, always calculating the hashCode for all instances of the object may be felt to be unnecessary.
since accessing a file system or network is relatively slow, such operations should be put off until they are absolutely required.

Lazy initialization has two objectives :

    delay an expensive operation until it's absolutely necessary
    store the result of that expensive operation, such that you won't need to repeat it again

http://www.javapractices.com/topic/TopicAction.do?Id=34

Tuesday, November 20, 2012

Memento pattern




  • Memento Design Pattern


Intent

    Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later.
    A magic cookie that encapsulates a “check point” capability.
    Promote undo or rollback to full object status.


Rules of thumb


    Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
    Command can use Memento to maintain the state required for an undo operation.
    Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.
http://sourcemaking.com/design_patterns/memento




  • Memento pattern


The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

The memento pattern is implemented with two objects: the originator and a caretaker. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.

Classic examples of the memento pattern include the seed of a pseudorandom number generator (it will always produce the same sequence thereafter when initialized with the seed state) and the state in a finite state machine.

http://en.wikipedia.org/wiki/Memento_pattern

Template Method Pattern



  • Template Method Design Pattern

Intent

    Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Rules of thumb

    Strategy is like Template Method except in its granularity.
    Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
    Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
    Factory Method is a specialization of Template Method.
http://sourcemaking.com/design_patterns/template_method



  • Template method pattern

 the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure
 http://en.wikipedia.org/wiki/Template_method_pattern

State pattern



  • State Design Pattern


Intent

    Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
    An object-oriented state machine
    wrapper + polymorphic wrappee + collaboration


Example


The State pattern allows an object to change its behavior when its internal state changes. This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.


Rules of thumb

    State objects are often Singletons.
    Flyweight explains when and how State objects can be shared.
    Interpreter can use State to define parsing contexts.
    Strategy has 2 different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
    The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
    The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the “context” object causes it to select from its “palette” of Strategy objects.

http://sourcemaking.com/design_patterns/state




  • State pattern

The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtime
http://en.wikipedia.org/wiki/State_pattern

Null Object pattern



  • Null Object pattern

a Null Object is an object with defined neutral ("null") behavior.
The Null Object design pattern describes the uses of such objects and their behavior (or lack thereof).

Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

For example, a function may retrieve a list of files in a directory and perform some action on each. In the case of an empty directory, one response may be to throw an exception or return a null reference rather than a list. Thus, the code which expects a list must verify that it in fact has one before continuing, which can complicate the design.

By returning a null object (i.e. an empty list) instead, there is no need to verify that the return value is in fact a list. The calling function may simply iterate the list as normal, effectively doing nothing. It is, however, still possible to check whether the return value is a null object (e.g. an empty list) and react differently if desired.

The null object pattern can also be used to act as a stub for testing if a certain feature, such as a database, is not available for testing.

http://en.wikipedia.org/wiki/Null_Object_pattern



  • Rules of thumb


    The Null Object class is often implemented as a Singleton. Since a null object usually does not have any state, its state can’t change, so multiple instances are identical. Rather than use multiple identical instances, the system can just use a single instance repeatedly.
    If some clients expect the null object to do nothing one way and some another, multiple NullObject classes will be required. If the do nothing behavior must be customized at run time, the NullObject class will require pluggable variables so that the client can specify how the null object should do nothing (see the discussion of pluggable adaptors in the Adapter pattern). This may generally be a symptom of the AbstractObject not having a well defined (semantic) interface.
    A Null Object does not transform to become a Real Object. If the object may decide to stop providing do nothing behavior and start providing real behavior, it is not a null object. It may be a real object with a do nothing mode, such as a controller which can switch in and out of read-only mode. If it is a single object which must mutate from a do nothing object to a real one, it should be implemented with the State pattern or perhaps the Proxy pattern. In this case a Null State may be used or the proxy may hold a Null Object.
    The use of a null object can be similar to that of a Proxy, but the two patterns have different purposes. A proxy provides a level of indirection when accessing a real subject, thus controlling access to the subject. A null collaborator does not hide a real object and control access to it, it replaces the real object. A proxy may eventually mutate to start acting like a real subject. A null object will not mutate to start providing real behavior, it will always provide do nothing behavior.
    A Null Object can be a special case of the Strategy pattern. Strategy specifies several ConcreteStrategy classes as different approaches for accomplishing a task. If one of those approaches is to consistently do nothing, that ConcreteStrategy is a NullObject. For example, a Controller is a View’s Strategy for handling input, and NoController is the Strategy that ignores all input.
    A Null Object can be a special case of the State pattern. Normally, each ConcreteState has some do nothing methods because they’re not appropriate for that state. In fact, a given method is often implemented to do something useful in most states but to do nothing in at least one state. If a particular ConcreteState implements most of its methods to do nothing or at least give null results, it becomes a do nothing state and as such is a null state.
    A Null Object can be used to allow a Visitor to safely visit a hierarchy and handle the null situation.
    Null Object is a concrete collaborator class that acts as the collaborator for a client which needs one. The null behavior is not designed to be mixed into an object that needs some do nothing behavior. It is designed for a class which delegates to a collaborator all of the behavior that may or may not be do nothing behavior
   
    http://sourcemaking.com/design_patterns/null_object

Mediator pattern



  • Mediator Design Pattern

Intent

    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 lets you vary their interaction independently.
    Design an intermediary to decouple many peers.
    Promote the many-to-many relationships between interacting peers to “full object status”.
   
Example

The Mediator defines an object that controls how a set of objects interact. Loose coupling between colleague objects is achieved by having colleagues communicate with the Mediator, rather than with each other. The control tower at a controlled airport demonstrates this pattern very well. The pilots of the planes approaching or departing the terminal area communicate with the tower rather than explicitly communicating with one another. The constraints on who can take off or land are enforced by the tower. It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.

Rules of thumb

    Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers. Command normally specifies a sender-receiver connection with a subclass. Mediator has senders and receivers reference each other indirectly. Observer defines a very decoupled interface that allows for multiple receivers to be configured at run-time.
    Mediator and Observer are competing patterns. The difference between them is that Observer distributes communication by introducing “observer” and “subject” objects, whereas a Mediator object encapsulates the communication between other objects. We’ve found it easier to make reusable Observers and Subjects than to make reusable Mediators.
    On the other hand, Mediator can leverage Observer for dynamically registering colleagues and communicating with them.
    Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communication between colleague objects, it routinely “adds value”, and it is known/referenced by the colleague objects (i.e. it defines a multidirectional protocol). In contrast, Facade defines a simpler interface to a subsystem, it doesn’t add new functionality, and it is not known by the subsystem classes (i.e. it defines a unidirectional protocol where it makes requests of the subsystem classes but not vice versa).
http://sourcemaking.com/design_patterns/mediator



  • Mediator pattern

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.
http://en.wikipedia.org/wiki/Mediator_pattern

Interpreter Pattern


Interpreter Design Pattern

Intent

    Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
    Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.

Rules of thumb
    Considered in its most general form (i.e. an operation distributed over a class hierarchy based on the Composite pattern), nearly every use of the Composite pattern will also contain the Interpreter pattern. But the Interpreter pattern should be reserved for those cases in which you want to think of this class hierarchy as defining a language.
    Interpreter can use State to define parsing contexts.
    The abstract syntax tree of Interpreter is a Composite (therefore Iterator and Visitor are also applicable).
    Terminal symbols within Interpreter’s abstract syntax tree can be shared with Flyweight.
    The pattern doesn’t address parsing. When the grammar is very complex, other techniques (such as a parser) are more appropriate.


http://sourcemaking.com/design_patterns/interpreter


Interpreter pattern
the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence
http://en.wikipedia.org/wiki/Interpreter_pattern

Chain of Responsibility Pattern



  • Rules of thumb


    Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers.
    Chain of Responsibility can use Command to represent requests as objects.
    Chain of Responsibility is often applied in conjunction with Composite. There, a component’s parent can act as its successor
http://sourcemaking.com/design_patterns/chain_of_responsibility



  • Chain-of-responsibility pattern

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. A mechanism also exists for adding new processing objects to the end of this chain.
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

Monday, November 19, 2012

Prototype Pattern



  • Prototype Pattern


Intent

    Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
    The new operator considered harmful.

Rules of thumb


    Sometimes creational patterns are competitors: there are cases when either Prototype or Abstract Factory could be used properly. At other times they are complementory: Abstract Factory might store a set of Prototypes from which to clone and return product objects. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
    Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype.
    Factory Method: creation through inheritance. Protoype: creation through delegation.
    Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Protoype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
    Prototype doesn’t require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but doesn’t require Initialize.
    Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.
    Prototype co-opts one instance of a class for use as a breeder of all future instances.
    Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. In this context, Prototype can avoid expensive “creation from scratch”, and support cheap cloning of a pre-initialized prototype.
    Prototype is unique among the other creational patterns in that it doesn’t require a class – only an object. Object-oriented languages like Self and Omega that do away with classes completely rely on prototypes for creating new objects

http://sourcemaking.com/design_patterns/prototype



  • Prototype pattern


The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

    avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
    avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

http://en.wikipedia.org/wiki/Prototype_pattern

Object Pool Pattern



  • Object Pool Design Pattern


Intent

Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

Problem

Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created.


Example

Do you like bowling? If you do, you probably know that you should change your shoes when you getting the bowling club. Shoe shelf is wonderful example of Object Pool. Once you want to play, you’ll get your pair (aquireReusable) from it. After the game, you’ll return shoes back to the shelf (releaseReusable).

Rules of thumb

    The Factory Method pattern can be used to encapsulate the creation logic for objects. However, it does not manage them after their creation, the object pool pattern keeps track of the objects it creates.
    Object Pools are usually implemented as Singletons.

http://sourcemaking.com/design_patterns/object_pool



  • Object pool pattern


The object pool pattern is a software creational design pattern that uses a set of initialised objects kept ready to use, rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished, it returns the object, which is a specific type of factory object, to the pool rather than destroying it

http://en.wikipedia.org/wiki/Object_pool_pattern



  • Object Pool Pattern

The Object Pool lets others "check out" objects from its pool, when those objects are no longer needed by their processes, they are returned to the pool in order to be reused.
http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/objectpool.html

Builder Pattern



  • Builder  Pattern


Intent

    Separate the construction of a complex object from its representation so that the same construction process can create different representations.
    Parse a complex representation, create one of several targets.
http://sourcemaking.com/design_patterns/builder



  • Builder pattern

he intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance with the composite pattern.
http://en.wikipedia.org/wiki/Builder_pattern

Private class data pattern



  • Private class data pattern


Intent

The private class data design pattern seeks to reduce exposure of attributes by limiting their visibility. It reduces the number of class attributes by encapsulating them in single Data object. It allows the class designer to remove write privilege of attributes that are intended to be set only during construction, even from methods of the target class.

Consequences

The consequences of using this design pattern include the following:

    Controlling write access to class attributes;
    Separating of data from methods that use it;
    Encapsulating class attribute (data) initialization; and
    Providing new type of final: final after constructor.

http://en.wikipedia.org/wiki/Private_class_data_pattern

Sunday, November 4, 2012

Proxy Pattern



  • The Proxy Pattern

Intent
Provide a surrogate or placeholder for another object to control access to it

A proxy is
› a person authorized to act for another person
› an agent or substitute
› the authority to act for another

There are situations in which a client does not or can not reference an
object directly, but wants to still interact with the object

A proxy object can act as the intermediary between the client and the target
object

http://userpages.umbc.edu/~tarr/dp/lectures/Proxy.pdf



  • Intent

    Provide a surrogate or placeholder for another object to control access to it.
    Use an extra level of indirection to support distributed, controlled, or intelligent access.
    Add a wrapper and delegation to protect the real component from undue complexity.

Problem

You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

Example

The Proxy provides a surrogate or place holder to provide access to an object. A check or bank draft is a proxy for funds in an account. A check can be used in place of cash for making purchases and ultimately controls access to cash in the issuer’s account.

Rules of thumb

    Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
    Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.
 
http://sourcemaking.com/design_patterns/proxy



  • Proxy pattern

A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
http://en.wikipedia.org/wiki/Proxy_pattern

flyweight pattern



Basit nesneler olusturmak istiyorsunuz ve bu nesnelerin bazi
veri degerleri farklidir. Nesnelerdem çok fazla
olusturdugunuzda bellek fazla kullanilacaksa, nesnelerden 1
tane olusturup, farkli verileri bu nesneye metot parametresi
olarak göndermek daha iyi olacaktir.

Bu kullanim flyweight sablonudur.

Örnegin; bir kelime islemci uygulamasindaki her harf için bir
nesne olusturmaktansa harfin bir kopyasi olusturulur ve
kullanilacagi yerlerde bu kopyanin referansi kullanilir.

http://members.comu.edu.tr/msahin/courses/ust_duzey_files/patterns/flyweight.pdf

Abstract Factory pattern


Abstract Factory pattern

Intent

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

The Abstract Factory pattern is very similar to the Factory Method pattern.
One difference between the two is that with the Abstract Factory pattern, a
class delegates the responsibility of object instantiation to another object
via composition whereas the Factory Method pattern uses inheritance and
relies on a subclass to handle the desired object instantiation.

Actually, the delegated object frequently uses factory methods to perform
the instantiation


Applicability
Use the Abstract Factory pattern in any of the following situations:

A system should be independent of how its products are created,
composed, and represented
class can't anticipate the class of objects it must create
A system must use just one of a set of families of products
A family of related product objects is designed to be used together, and you
need to enforce this constrain

http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf