<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Argholka</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Argholka"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Argholka"/>
	<updated>2026-09-15T19:55:55Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=54075</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=54075"/>
		<updated>2011-10-21T20:06:41Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
A design Pattern &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Patterns] - Wikipedia&amp;lt;/ref&amp;gt;&amp;lt;ref&amp;gt;[http://www.javacamp.org/designPattern/ JavaCamp]&amp;lt;/ref&amp;gt; is commonly used almost all over the Software industry to create highly scalable and efficient software. In this article, we focus primarily on four design patterns: [http://en.wikipedia.org/wiki/Singleton_pattern Singleton], [http://en.wikipedia.org/wiki/Adapter_pattern Adapter], [http://en.wikipedia.org/wiki/Command_pattern Command] and [http://en.wikipedia.org/wiki/Strategy_pattern Strategy]. For purpose of effective explanation as well as to give an alternative viewpoint, we have supplemented all the patterns with code examples in [http://en.wikipedia.org/wiki/Java Java].&lt;br /&gt;
&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
In Software, a design pattern is a reusable solution which is a template to commonly occurring design problems in software design. Design pattern is never a code - solution to the problem; it is always an explanation or set of rules about how common problems in design can be solved. Using design patterns in development leads to more robust and effective software. &lt;br /&gt;
&lt;br /&gt;
Design Patterns can be subdivided into three major types:&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Creational_pattern Creational patterns] - determine how objects are created&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Structural_pattern Structural patterns] - define  how objects are related to each other&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral patterns] - define how objects communicate with each other&lt;br /&gt;
&lt;br /&gt;
The singleton is a creational pattern, the adapter is a structural pattern and command and strategy are behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of [http://en.wikipedia.org/wiki/Lazy_instantiation lazy instantiation] where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the '''''getInstance''''' method at the same time, [http://en.wikipedia.org/wiki/Race_condition race conditions] may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method [http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html synchronized].&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is [http://en.wikipedia.org/wiki/Thread_safety thread safe] because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as double checked locking &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Double-checked_locking Double Checked Locking] - Wikipedia &amp;lt;/ref&amp;gt; and using &amp;quot;enum&amp;quot; data-type as outlined in the book Effective Java &amp;lt;ref&amp;gt;[http://java.sun.com/docs/books/effective/ Effective Java]- Effective Java 2nd Edition By Joshua Bloch&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible [http://en.wikipedia.org/wiki/Interface_(object-oriented_programming) interfaces] to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country &amp;lt;ref&amp;gt;Head First Design Patterns By Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is a Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using [http://www.khelll.com/blog/ruby/delegation-in-ruby/ delegation] in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Properties of the Command Pattern ===&lt;br /&gt;
*The Command Pattern successfully decouples the object which invokes the operation from the object which actually performs the operation.&lt;br /&gt;
*CommandObjects are like normal first-class objects. They can be easily extended, manipulated and handled like every other object.&lt;br /&gt;
*The Command pattern can easily handle an undo operation. By maintaining a history of the commands executed, we can undo the last operations in the order that they were performed. &lt;br /&gt;
*The Command pattern lets us create a group of operations to be performed in one call of execute. This functionality is called as MacroOperations or Composite Commands. Such commands consist of multiple actions related to different Receivers which can be performed one after the other on just one invocation.&lt;br /&gt;
*Due to the excellent structure of the Command pattern, it is easily extensible and hence it is easy to declare and add new Commands.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
'' Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&amp;lt;ref&amp;gt;Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&amp;lt;/ref&amp;gt; &amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/strategy Source Matching] - Strategy Pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&amp;lt;ref&amp;gt;[http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/22/applying-strategy-pattern-instead-of-using-switch-statements.aspx Using Strategy instead of switch] - Microsoft Blog&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when&amp;lt;ref&amp;gt;[http://www.oodesign.com/ OODesign] - Startegy Pattern&amp;lt;/ref&amp;gt;:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
Design patterns are an essential part of the design process and should be used to create a robust and effective design for the software. The four patterns discussed in this chapter are unique and are most efficient when applied in the correct situations. Singleton pattern can be used when the design calls for a class which has to be instantiated only once. Adapter pattern can be used when the client software has to work with external components or libraries. Command pattern can be used when a single function or action has to linked to multiple commands at different times. Strategy Pattern can be used when we have a choice of using multiple algorithms which work towards achieving the same goal.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=54047</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=54047"/>
		<updated>2011-10-21T19:33:52Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Software Design Patterns */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
A design Pattern &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Patterns] - Wikipedia&amp;lt;/ref&amp;gt; is commonly used almost all over the Software industry to create highly scalable and efficient software. In this article, we focus primarily on four design patterns: [http://en.wikipedia.org/wiki/Singleton_pattern Singleton], [http://en.wikipedia.org/wiki/Adapter_pattern Adapter], [http://en.wikipedia.org/wiki/Command_pattern Command] and [http://en.wikipedia.org/wiki/Strategy_pattern Strategy]. For purpose of effective explanation as well as to give an alternative viewpoint, we have supplemented all the patterns with code examples in [http://en.wikipedia.org/wiki/Java Java].&lt;br /&gt;
&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
In Software, a design pattern is a reusable solution which is a template to commonly occurring design problems in software design. Design pattern is never a code - solution to the problem; it is always an explanation or set of rules about how common problems in design can be solved. Using design patterns in development leads to more robust and effective software. &lt;br /&gt;
&lt;br /&gt;
Design Patterns can be subdivided into three major types:&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Creational_pattern Creational patterns] - determine how objects are created&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Structural_pattern Structural patterns] - define  how objects are related to each other&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral patterns] - define how objects communicate with each other&lt;br /&gt;
&lt;br /&gt;
The singleton is a creational pattern, the adapter is a structural pattern and command and strategy are behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of [http://en.wikipedia.org/wiki/Lazy_instantiation lazy instantiation] where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the '''''getInstance''''' method at the same time, [http://en.wikipedia.org/wiki/Race_condition race conditions] may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method [http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html synchronized].&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is [http://en.wikipedia.org/wiki/Thread_safety thread safe] because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as double checked locking &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Double-checked_locking Double Checked Locking] - Wikipedia &amp;lt;/ref&amp;gt; and using &amp;quot;enum&amp;quot; data-type as outlined in the book Effective Java &amp;lt;ref&amp;gt;[http://java.sun.com/docs/books/effective/ Effective Java]- Effective Java 2nd Edition By Joshua Bloch&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible [http://en.wikipedia.org/wiki/Interface_(object-oriented_programming) interfaces] to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country &amp;lt;ref&amp;gt;Head First Design Patterns By Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is a Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using [http://www.khelll.com/blog/ruby/delegation-in-ruby/ delegation] in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Properties of the Command Pattern ===&lt;br /&gt;
*The Command Pattern successfully decouples the object which invokes the operation from the object which actually performs the operation.&lt;br /&gt;
*CommandObjects are like normal first-class objects. They can be easily extended, manipulated and handled like every other object.&lt;br /&gt;
*The Command pattern can easily handle an undo operation. By maintaining a history of the commands executed, we can undo the last operations in the order that they were performed. &lt;br /&gt;
*The Command pattern lets us create a group of operations to be performed in one call of execute. This functionality is called as MacroOperations or Composite Commands. Such commands consist of multiple actions related to different Receivers which can be performed one after the other on just one invocation.&lt;br /&gt;
*Due to the excellent structure of the Command pattern, it is easily extensible and hence it is easy to declare and add new Commands.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
'' Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&amp;lt;ref&amp;gt;Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Conclusion ===&lt;br /&gt;
Design patterns are an essential part of the design process and should be used to create a robust and effective design for the software. The four patterns discussed in this chapter are unique and are most efficient when applied in the correct situations. Singleton pattern can be used when the design calls for a class which has to be instantiated only once. Adapter pattern can be used when the client software has to work with external components or libraries. Command pattern can be used when a single function or action has to linked to multiple commands at different times. Strategy Pattern can be used when we have a choice of using multiple algorithms which work towards achieving the same goal.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=54045</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=54045"/>
		<updated>2011-10-21T19:27:29Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
A design Pattern &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Patterns] - Wikipedia&amp;lt;/ref&amp;gt; is commonly used almost all over the Software industry to create highly scalable and efficient software. In this article, we focus primarily on four design patterns: [http://en.wikipedia.org/wiki/Singleton_pattern Singleton], [http://en.wikipedia.org/wiki/Adapter_pattern Adapter], [http://en.wikipedia.org/wiki/Command_pattern Command] and [http://en.wikipedia.org/wiki/Strategy_pattern Strategy]. For purpose of effective explanation as well as to give an alternative viewpoint, we have supplemented all the patterns with code examples in [http://en.wikipedia.org/wiki/Java Java].&lt;br /&gt;
&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
In Software, a design pattern is a reusable solution which is a general template to a commonly occurring design problems in software design. Design pattern is never a code - solution to the problem; it is always a generic template or explanation or set of rules about how common problems in design can be solved. Using design patterns in development leads to more robust and effective software. &lt;br /&gt;
&lt;br /&gt;
Design Patterns can be subdivided into three major types:&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Creational_pattern Creational patterns] - determine how objects are created&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Structural_pattern Structural patterns] - define  how objects are related to each other&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral patterns] - define how objects communicate with each other&lt;br /&gt;
&lt;br /&gt;
The singleton is a creational pattern, the adapter is a structural pattern and command and strategy are behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of [http://en.wikipedia.org/wiki/Lazy_instantiation lazy instantiation] where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the '''''getInstance''''' method at the same time, [http://en.wikipedia.org/wiki/Race_condition race conditions] may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method [http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html synchronized].&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is [http://en.wikipedia.org/wiki/Thread_safety thread safe] because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as double checked locking &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Double-checked_locking Double Checked Locking] - Wikipedia &amp;lt;/ref&amp;gt; and using &amp;quot;enum&amp;quot; data-type as outlined in the book Effective Java &amp;lt;ref&amp;gt;[http://java.sun.com/docs/books/effective/ Effective Java]- Effective Java 2nd Edition By Joshua Bloch&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible [http://en.wikipedia.org/wiki/Interface_(object-oriented_programming) interfaces] to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country &amp;lt;ref&amp;gt;Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author)&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is a Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using [http://www.khelll.com/blog/ruby/delegation-in-ruby/ delegation] in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Properties of the Command Pattern ===&lt;br /&gt;
*The Command Pattern successfully decouples the object which invokes the operation from the object which actually performs the operation.&lt;br /&gt;
*CommandObjects are like normal first-class objects. They can be easily extended, manipulated and handled like every other object.&lt;br /&gt;
*The Command pattern can easily handle an undo operation. By maintaining a history of the commands executed, we can undo the last operations in the order that they were performed. &lt;br /&gt;
*The Command pattern lets us create a group of operations to be performed in one call of execute. This functionality is called as MacroOperations or Composite Commands. Such commands consist of multiple actions related to different Receivers which can be performed one after the other on just one invocation.&lt;br /&gt;
*Due to the excellent structure of the Command pattern, it is easily extensible and hence it is easy to declare and add new Commands.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
'' Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&amp;lt;ref&amp;gt;Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Conclusion ===&lt;br /&gt;
Design patterns are an essential part of the design process and should be used to create a robust and effective design for the software. The four patterns discussed in this chapter are unique and are most efficient when applied in the correct situations. Singleton pattern can be used when the design calls for a class which has to be instantiated only once. Adapter pattern can be used when the client software has to work with external components or libraries. Command pattern can be used when a single function or action has to linked to multiple commands at different times. Strategy Pattern can be used when we have a choice of using multiple algorithms which work towards achieving the same goal.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=54043</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=54043"/>
		<updated>2011-10-21T19:13:59Z</updated>

		<summary type="html">&lt;p&gt;Argholka: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
A design Pattern &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Patterns] - Wikipedia&amp;lt;/ref&amp;gt; is commonly used almost all over the Software industry to create highly scalable and efficient software. In this article, we focus primarily on four design patterns: [http://en.wikipedia.org/wiki/Singleton_pattern Singleton], [http://en.wikipedia.org/wiki/Adapter_pattern Adapter], [http://en.wikipedia.org/wiki/Command_pattern Command] and [http://en.wikipedia.org/wiki/Strategy_pattern Strategy]. For purpose of effective explanation as well as to give an alternative viewpoint, we have supplemented all the patterns with code examples in [http://en.wikipedia.org/wiki/Java Java].&lt;br /&gt;
&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
In Software, a design pattern is a reusable solution which is a general template to a commonly occurring design problems in software design. Design pattern is never a code - solution to the problem; it is always a generic template or explanation or set of rules about how common problems in design can be solved. Using design patterns in development leads to more robust and effective software. &lt;br /&gt;
&lt;br /&gt;
Design Patterns can be subdivided into three major types:&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Creational_pattern Creational patterns] - determine how objects are created&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Structural_pattern Structural patterns] - define  how objects are related to each other&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral patterns] - define how objects communicate with each other&lt;br /&gt;
&lt;br /&gt;
The singleton is a creational pattern, the adapter is a structural pattern and command and strategy are behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of [http://en.wikipedia.org/wiki/Lazy_instantiation lazy instantiation] where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the '''''getInstance''''' method at the same time, [http://en.wikipedia.org/wiki/Race_condition race conditions] may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method [http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html synchronized].&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is [http://en.wikipedia.org/wiki/Thread_safety thread safe] because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as double checked locking &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Double-checked_locking Double Checked Locking] - Wikipedia &amp;lt;/ref&amp;gt; and using &amp;quot;enum&amp;quot; data-type as outlined in the book Effective Java &amp;lt;ref&amp;gt;[http://java.sun.com/docs/books/effective/ Effective Java]- Effective Java 2nd Edition By Joshua Bloch&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible [http://en.wikipedia.org/wiki/Interface_(object-oriented_programming) interfaces] to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country &amp;lt;ref&amp;gt;Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author)&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is a Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using [http://www.khelll.com/blog/ruby/delegation-in-ruby/ delegation] in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Properties of the Command Pattern ===&lt;br /&gt;
*The Command Pattern successfully decouples the object which invokes the operation from the object which actually performs the operation.&lt;br /&gt;
*CommandObjects are like normal first-class objects. They can be easily extended, manipulated and handled like every other object.&lt;br /&gt;
*The Command pattern can easily handle an undo operation. By maintaining a history of the commands executed, we can undo the last operations in the order that they were performed. &lt;br /&gt;
*The Command pattern lets us create a group of operations to be performed in one call of execute. This functionality is called as MacroOperations or Composite Commands. Such commands consist of multiple actions related to different Receivers which can be performed one after the other on just one invocation.&lt;br /&gt;
*Due to the excellent structure of the Command pattern, it is easily extensible and hence it is easy to declare and add new Commands.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
'' Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&amp;lt;ref&amp;gt;Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Conclusion ===&lt;br /&gt;
We conclude that Design patterns are an essential part of the design process and should be used for creating a robust and effective software design. The four patterns discussed in this chapter are unique and are efficient when used in the right way.&lt;br /&gt;
Singleton Pattern can be used when the design calls for a class which can be instantiated with only one object.&lt;br /&gt;
Adapter Pattern&lt;br /&gt;
Command Pattern can be used when there is a need of linking a single function or action to multiple commands at different times.&lt;br /&gt;
Strategy Pattern can be used when we have the choice of using multiple algorithms which work towards achieving the same goal. &lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53917</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53917"/>
		<updated>2011-10-21T03:41:48Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_patterns_%28computer_science%29 Design Pattern] is commonly used almost all over the Software industry to create highly scalable and efficient software. In this article, we focus primarily on four design patterns: [http://en.wikipedia.org/wiki/Singleton_pattern Singleton], [http://en.wikipedia.org/wiki/Adapter_pattern Adapter], [http://en.wikipedia.org/wiki/Command_pattern Command] and [http://en.wikipedia.org/wiki/Strategy_pattern Strategy]. For purpose of effective explanation, we have supplemented all the patterns with code examples in [http://en.wikipedia.org/wiki/Java Java].&lt;br /&gt;
&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
In Software, a design pattern is a reusable solution which is a general template to a commonly occurring design problems in software design. Design pattern is never a code - solution to the problem; it is always a generic template or explanation or set of rules about how common problems in design can be solved.&lt;br /&gt;
&lt;br /&gt;
Design Patterns can be subdivided into three major types; [http://en.wikipedia.org/wiki/Creational_pattern Creational Patterns], [http://en.wikipedia.org/wiki/Structural_pattern Structural Patterns] and [http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Patterns].&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Properties of the Command Pattern ===&lt;br /&gt;
*The Command Pattern successfully decouples the object which invokes the operation from the object which actually performs the operation.&lt;br /&gt;
*CommandObjects are like normal first-class objects. They can be easily extended, manipulated and handled like every other object.&lt;br /&gt;
*The Command pattern can easily handle an undo operation. By maintaining a history of the commands executed, we can undo the last operations in the order that they were performed. &lt;br /&gt;
*The Command pattern lets us create a group of operations to be performed in one call of execute. This functionality is called as MacroOperations or Composite Commands. Such commands consist of multiple actions related to different Receivers which can be performed one after the other on just one invocation.&lt;br /&gt;
*Due to the excellent structure of the Command pattern, it is easily extensible and hence it is easy to declare and add new Commands.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53915</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53915"/>
		<updated>2011-10-21T03:36:39Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_patterns_%28computer_science%29 Design Pattern] is commonly used almost all over the Software industry to create highly scalable and efficient software. In this article, we focus primarily on four design patterns: [http://en.wikipedia.org/wiki/Singleton_pattern Singleton], [http://en.wikipedia.org/wiki/Adapter_pattern Adapter], [http://en.wikipedia.org/wiki/Command_pattern Command] and [http://en.wikipedia.org/wiki/Strategy_pattern Strategy]. For purpose of effective explanation, we have supplemented all the patterns with code examples in [http://en.wikipedia.org/wiki/Java Java].&lt;br /&gt;
&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
In Software, a design pattern is a reusable solution which is a general template to a commonly occurring design problems in software design. Design pattern is never a code - solution to the problem; it is always a generic template or explanation or set of rules about how common problems in design can be solved.&lt;br /&gt;
&lt;br /&gt;
Design Patterns can be subdivided into three major types; [http://en.wikipedia.org/wiki/Creational_pattern Creational Patterns], [http://en.wikipedia.org/wiki/Structural_pattern Structural Patterns] and [http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Patterns].&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53914</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53914"/>
		<updated>2011-10-21T03:36:05Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
A Design Pattern is commonly used almost all over the Software industry to create highly scalable and efficient software. In this article, we focus primarily on four design patterns: [http://en.wikipedia.org/wiki/Singleton_pattern Singleton], [http://en.wikipedia.org/wiki/Adapter_pattern Adapter], [http://en.wikipedia.org/wiki/Command_pattern Command] and [http://en.wikipedia.org/wiki/Strategy_pattern Strategy]. For purpose of effective explanation, we have supplemented all the patterns with code examples in [http://en.wikipedia.org/wiki/Java Java].&lt;br /&gt;
&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
In Software, a design pattern is a reusable solution which is a general template to a commonly occurring design problems in software design. Design pattern is never a code - solution to the problem; it is always a generic template or explanation or set of rules about how common problems in design can be solved.&lt;br /&gt;
&lt;br /&gt;
Design Patterns can be subdivided into three major types; [http://en.wikipedia.org/wiki/Creational_pattern Creational Patterns], [http://en.wikipedia.org/wiki/Structural_pattern Structural Patterns] and [http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Patterns].&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53909</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53909"/>
		<updated>2011-10-21T03:32:21Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Software Design Patterns */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
In Software, a design pattern is a reusable solution which is a general template to a commonly occurring design problems in software design. Design pattern is never a code - solution to the problem; it is always a generic template or explanation or set of rules about how common problems in design can be solved.&lt;br /&gt;
&lt;br /&gt;
Design Patterns can be subdivided into three major types; [http://en.wikipedia.org/wiki/Creational_pattern Creational Patterns], [http://en.wikipedia.org/wiki/Structural_pattern Structural Patterns] and [http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Patterns].&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53902</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53902"/>
		<updated>2011-10-21T03:25:55Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Participants */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
*'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
*'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
*'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
*'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
*'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53900</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53900"/>
		<updated>2011-10-21T03:25:29Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
Command Pattern can be used when:&lt;br /&gt;
*We need one action/function which can be represented in many ways, like drop-down menu, buttons and popup menu.&lt;br /&gt;
*We need a callback function, i.e., register it somewhere to be called later.&lt;br /&gt;
*We need to specify and execute the request at different times.&lt;br /&gt;
*We need to undo an action by storing its states for later retrieving.&lt;br /&gt;
*We need to decouple the invoker Object from the Receiver Object.&lt;br /&gt;
*We need an easily extensible program structure. &lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53886</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53886"/>
		<updated>2011-10-21T03:21:10Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53885</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53885"/>
		<updated>2011-10-21T03:21:00Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53884</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53884"/>
		<updated>2011-10-21T03:20:40Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
A simple Example is shown below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
increment_by_20 = Proc.new { |n| n+20 }&lt;br /&gt;
increment_by_20.call 20&lt;br /&gt;
=&amp;gt; 40&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53876</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53876"/>
		<updated>2011-10-21T03:17:35Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using [http://www.ruby-doc.org/core-1.9.2/Proc.html Procs]. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53875</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53875"/>
		<updated>2011-10-21T03:17:14Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Strategy Pattern in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
[http://www.ruby-doc.org/core-1.9.2/Proc.html Proc] objects are used in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53874</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53874"/>
		<updated>2011-10-21T03:16:37Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
Proc objects are used in Ruby to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53873</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53873"/>
		<updated>2011-10-21T03:15:37Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
Proc objects are used in Ruby to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53871</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53871"/>
		<updated>2011-10-21T03:15:06Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Strategy Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] encapsulates a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''[http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is a pattern which [http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 encapsulates] a defined family of [http://en.wikipedia.org/wiki/Algorithms algorithms] and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like [http://en.wikipedia.org/wiki/Bubble_sort BubbleSort], [http://en.wikipedia.org/wiki/Quick_sort QuickSort], [http://en.wikipedia.org/wiki/Selection_sort SelectionSort] etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
Proc objects are used in Ruby to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53867</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53867"/>
		<updated>2011-10-21T03:11:25Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Formal definition */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The [http://en.wikipedia.org/wiki/Command_Pattern Command Pattern] encapsulates a request as an [http://en.wikipedia.org/wiki/Object_%28computer_science%29 object] and thereby allows us to parametrize other objects with different requests, queue or log requests and support UN-doable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a [http://en.wikipedia.org/wiki/Method_%28computer_programming%29 method] is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized [http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29 interface] – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
Proc objects are used in Ruby to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53863</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53863"/>
		<updated>2011-10-21T03:07:49Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
Proc objects are used in Ruby to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;br /&gt;
*Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author) &lt;br /&gt;
*Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53858</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53858"/>
		<updated>2011-10-21T03:05:57Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Software_engineering software engineering] the singleton pattern is a [http://en.wikipedia.org/wiki/Creational_pattern creational pattern] which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
===Formal Definition===&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The implementation of the adapter pattern is done using delegation in Ruby. This is very similar to the implementation in Java where the adapter class has a reference to the adaptee and defines the functions expected by the client class. The implementation in ruby is much simpler as a result of its dynamically typed nature.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
Proc objects are used in Ruby to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Design Patterns - Wikipedia ]&lt;br /&gt;
*[http://www.javacamp.org/designPattern/ Design Patterns - The Command Pattern]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Strategy_pattern Strategy Pattern - Wikipedia]&lt;br /&gt;
*[http://www.javaworld.com/javaworld/jw-06-2002/jw-0628-designpatterns.html Command Pattern - JavaWorld ]&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53845</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53845"/>
		<updated>2011-10-21T02:53:31Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Strategy Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strategy Pattern in Ruby ===&lt;br /&gt;
Proc objects are used in Ruby to implement Strategy pattern effectively. Proc are just objects referenced by symbols (which is the function name itself). These symbols can be passed as objects to any function in Ruby. &lt;br /&gt;
This enables us to implement strategy pattern. A Proc is normally invoked by using the Proc.call method. This proves to be the common interface which can be used to invoke any Proc at any time. &lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def strategy_a&lt;br /&gt;
     Proc.new { puts “Strategy-A Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def strategy_b&lt;br /&gt;
     Proc.new { puts “Strategy-B Called” }&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def setStrategy(func)&lt;br /&gt;
	@strategy = func&lt;br /&gt;
      end&lt;br /&gt;
      def callStrategy&lt;br /&gt;
	@strategy.call&lt;br /&gt;
      end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.setStrategy strategy_a&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-A called&lt;br /&gt;
c.setStrategy strategy_b&lt;br /&gt;
c.callStrategy&lt;br /&gt;
&amp;gt;&amp;gt; Strategy-B called&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53844</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53844"/>
		<updated>2011-10-21T02:52:39Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Implementation and Working */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation''' &lt;br /&gt;
*First we have to declare a common interface called Strategy (SortStrategy) which consists of the method that will be used by the ConcreteStrategy Class (i.e. sort (list)). &lt;br /&gt;
&lt;br /&gt;
*This interface is extended by the ConcreteStrategy classes i.e. ConcreteStrategyBubbleSort and ConcreteStrategyQuickSort in which they add their own implementation of the sort function. Note there that since these classes are first-class objects they can avail the use of any number of helper functions as long as they implement the sort function successfully. This is the sort function that will be called when the Client invokes it.&lt;br /&gt;
&lt;br /&gt;
*Thirdly, we have the Context i.e. SortContext which has a reference to the ConcreteStrategy Object within itself. It uses an instance of the common interface to refer to the ConcreteStrategy Object. Context will set the required Strategy in its setter method. It also creates a function i.e. doSort() which binds the ConcreteStrategy sort function to itself. Thus, the client has access to this function to invoke any of the Strategies.&lt;br /&gt;
&lt;br /&gt;
*Finally, we have the Client which has the instances of Context and the ConcreteStrategies. The Client decided which strategy to use and at what time. The Client uses the setter method of the Context to set a particular strategy and then call the operation by using the Context’s `doSort` method. Note here that the Client can replace or modify the Strategies at any point of time. We can also declare new Strategies just by declaring a new class to encapsulate the new Strategy. This saves centralized fat Class consisting of all the Strategies and if-else conditions to use those strategies. &lt;br /&gt;
&lt;br /&gt;
Strategy pattern thus successfully encapsulates different algorithms and makes them easy to use and extend.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53842</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53842"/>
		<updated>2011-10-21T02:51:08Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Implementation and Working */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		&lt;br /&gt;
                SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort();     //ConcreteStrategy for Bubble Sort&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy for Quick Sort	&lt;br /&gt;
		&lt;br /&gt;
                int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(bubble);          //Sort with Bubble Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		&lt;br /&gt;
		context.setStrategy(quick);           //Sort with Quick Sort&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53839</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53839"/>
		<updated>2011-10-21T02:49:54Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Strategy Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
=== Implementation and Working ===&lt;br /&gt;
Let us consider an example of Strategy pattern consisting of two Sorting Algorithms - Bubble Sort and Quick Sort.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SortStrategy {&lt;br /&gt;
	public void sort(int list[]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyBubbleSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Bubble Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ConcreteStrategyQuickSort implements SortStrategy{&lt;br /&gt;
	public void sort(int list[]){&lt;br /&gt;
		//Quick Sort Logic&lt;br /&gt;
	}&lt;br /&gt;
	//Additional Helper Functions&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortContext {&lt;br /&gt;
	private SortStrategy strategy;&lt;br /&gt;
&lt;br /&gt;
	public void doSort(int list[]){&lt;br /&gt;
		strategy.sort(list);&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public SortStrategy getStrategy() {&lt;br /&gt;
		return strategy;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void setStrategy(SortStrategy strategy) {&lt;br /&gt;
		this.strategy = strategy;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		SortContext context = new SortContext();&lt;br /&gt;
		ConcreteStrategyBubbleSort bubble = new ConcreteStrategyBubbleSort(); //ConcreteStrategy&lt;br /&gt;
		ConcreteStrategyQuickSort quick = new ConcreteStrategyQuickSort();	  //ConcreteStrategy	&lt;br /&gt;
		int[] array = {23,99,45,12,0,8,100,49,48};&lt;br /&gt;
		//Sort with Bubble Sort&lt;br /&gt;
		context.setStrategy(bubble);&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
		//Sort with Quick Sort&lt;br /&gt;
		context.setStrategy(quick);&lt;br /&gt;
		context.doSort(array);&lt;br /&gt;
	}	&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53838</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53838"/>
		<updated>2011-10-21T02:47:24Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Strategy Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53837</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53837"/>
		<updated>2011-10-21T02:47:08Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Strategy Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using &amp;quot;enum&amp;quot; data-type.&lt;br /&gt;
&lt;br /&gt;
The implementation of the singleton pattern in ruby is trivial as it is provided as a mixin by the library. All one has to do to make a class a singleton is to include the module &amp;quot;Singleton&amp;quot; in the definition of the class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
[[File:Strategy.png|thumb|center|600x600px|alt=Strategy Pattern|Figure 2. Structure of the Strategy Pattern.]]&lt;br /&gt;
*'''Strategy'''&lt;br /&gt;
&lt;br /&gt;
Strategy defines a common interface to be used and implemented by the actual Strategy Object – which can also be named as ConcreteStrategy. The function(s) declared in this interface are used by the Context to invoke the actual Strategy.&lt;br /&gt;
&lt;br /&gt;
*'''ConcreteStrategy'''&lt;br /&gt;
&lt;br /&gt;
ConcreteStrategy is the enlightened one in this pattern. This class encapsulates the required algorithmic functionality into the function exposed by the Strategy interface. Thus, all the logic to do the work lies in the ConcreteStrategy. By the pattern definition, there can be multiple ConcreteStrategys. &lt;br /&gt;
&lt;br /&gt;
*'''Context'''&lt;br /&gt;
&lt;br /&gt;
Context contains the reference to the ConcreteStrategy Object. This reference has to be configured prior to invoking the Strategy which is also handled by the Context. Additionally, it can also accept parameters which are to be passed on to the ConcreteStrategy Object. If the Strategy needs to access data from the Context, it might declare an interface to do so.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Strategy.png&amp;diff=53833</id>
		<title>File:Strategy.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Strategy.png&amp;diff=53833"/>
		<updated>2011-10-21T02:44:39Z</updated>

		<summary type="html">&lt;p&gt;Argholka: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53831</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53831"/>
		<updated>2011-10-21T02:43:49Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Strategy Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
=== Formal Definition ===&lt;br /&gt;
''Strategy pattern is a pattern which encapsulates a defined family of algorithms and thus makes them interchangeable. Thus, Strategy pattern allows the Client to change algorithms according to his will. Execution of the Algorithm will take place through a crystallized and common interface.''&lt;br /&gt;
&lt;br /&gt;
Let’s take a real world example to understand this pattern much better. Consider a Program where you have to sort a list of numbers. Note that the list of numbers is the data which is common to all algorithms here. If we were to write a program with one class consisting of all the algorithms as functions like BubbleSort, QuickSort, SelectionSort etc., the class would become too hard and huge to handle. The Program would consist of a central if-else OR switch case which would use different algorithms according to the Client input. Now, if we need to add another algorithm into this program, we have to add another function and add another else-if condition OR a switch case which is too tedious and dangerous. If we make one mistake in writing this code, we might end up with a broken program.&lt;br /&gt;
&lt;br /&gt;
Strategy Pattern aims at eliminating this problem by defining classes encapsulating different sorting algorithms and then let the Client/user use a common interface to set and call different algorithms at will.&lt;br /&gt;
&lt;br /&gt;
=== Common Applications ===&lt;br /&gt;
The strategy pattern should be used when:&lt;br /&gt;
*We have different versions of an algorithm to be used in our program.&lt;br /&gt;
*We have a class which displays different behavior – or a class which has to be configured to display different behaviors.&lt;br /&gt;
*We have a class which consists of different operations which are inefficiently expressed as multiple if-else statements or switch cases.&lt;br /&gt;
*We have an algorithm which is to be implemented in such a say that the user should know nothing about it. Thus, algorithm should be encapsulated from the user.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53826</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53826"/>
		<updated>2011-10-21T02:41:42Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Command Pattern in Ruby ===&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
&lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53821</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53821"/>
		<updated>2011-10-21T02:40:30Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Implementation Example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53819</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53819"/>
		<updated>2011-10-21T02:39:12Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Implementation Example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			     // Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	           //Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand);                     // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		           // Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53818</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53818"/>
		<updated>2011-10-21T02:38:41Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee. The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the&lt;br /&gt;
//RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
&lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
&lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
=== Implementation Example ===&lt;br /&gt;
For the implementation Example, lets take a look at how we can implement the Homework function in the example mentioned at the beginning of the pattern explanation.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			// Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	//Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand); // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		// Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53811</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53811"/>
		<updated>2011-10-21T02:33:54Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Formal definition */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee.&lt;br /&gt;
&lt;br /&gt;
The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the //RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
''The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.''&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53810</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53810"/>
		<updated>2011-10-21T02:33:33Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Types===&lt;br /&gt;
There are two types of adapters&lt;br /&gt;
&lt;br /&gt;
* Object adapters - The adapter described in the example is a object adapter. This uses composition to adapt one class to another.&lt;br /&gt;
* Class adapters -This type of adapter requires multiple inheritance and works by subclassing both the interfaces.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
The adapter pattern is mostly used to adapt to changing third party vendor libraries. Suppose a system works with an external vendor library and suppose we change vendors and the new vendor library implements a different interface. Now the client class expects a different interface and hence it becomes incompatible with the vendor library. We do not want to rewrite the client code and we cannot change the vendor library. The adapter pattern is ideally suited to solve this problem.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
Before describing anything let us establish some common terminology here.The vendor class is called '''adpatee''', the class which performs the work of the middleman is called the '''adapter''' and the interface implemented by the client is called the '''target interface'''.&lt;br /&gt;
&lt;br /&gt;
The adapter is realized using a class which implements the target interface and has a reference to the adaptee. The implementation translates functional calls made against the target interface into calls made against the interface implemented by the adaptee.&lt;br /&gt;
&lt;br /&gt;
The adapter decouples the client from the vendor interface. If the vendor changes a new adapter can be written to accommodate this change.&lt;br /&gt;
&lt;br /&gt;
The following is an Java version of the Square peg round hole example presented in class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface RoundObject {&lt;br /&gt;
	public float getRadius();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Round hole expects the object It test for in the fits function to implement the &lt;br /&gt;
//RoundObject Interface&lt;br /&gt;
public class RoundHole implements RoundObject {&lt;br /&gt;
	private float radius;&lt;br /&gt;
	public RoundHole(float radius){&lt;br /&gt;
		this.radius = radius;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return radius;&lt;br /&gt;
	}&lt;br /&gt;
	public boolean fits(RoundObject peg){&lt;br /&gt;
	return peg.getRadius() &amp;lt;= radius;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface SquareObject {&lt;br /&gt;
	public float getWidth();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Square peg implements SquareObject which is incompatible with RoundObject&lt;br /&gt;
//Hence RoundHole cannot test if the SquarePeg object fits directly&lt;br /&gt;
public class SquarePeg implements SquareObject{&lt;br /&gt;
	private float width;&lt;br /&gt;
	public SquarePeg(float width){&lt;br /&gt;
		this.width = width;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public float getWidth(){&lt;br /&gt;
		return width;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//The adapter adapts the SquarePeg object so that it is compatible with the //RoundObject Interface. The adapter implements RoundObject Interface and also has a reference to the SqurePeg Object. &lt;br /&gt;
public class SquarePegAdapter implements RoundObject {&lt;br /&gt;
	private SquarePeg squarePeg;&lt;br /&gt;
	&lt;br /&gt;
	public SquarePegAdapter(SquarePeg squarePeg){&lt;br /&gt;
		this.squarePeg = squarePeg;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public float getRadius(){&lt;br /&gt;
		return (float) Math.sqrt(Math.pow(squarePeg.getWidth()/2,2)*2);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Hence this test works &lt;br /&gt;
public class AdapterTest {&lt;br /&gt;
	public static void main(String[] args) {&lt;br /&gt;
		RoundObject adapter = new SquarePegAdapter(new SquarePeg(100));&lt;br /&gt;
		RoundHole hole = new RoundHole(10);&lt;br /&gt;
		if(hole.fits(adapter)){&lt;br /&gt;
			System.out.println(&amp;quot;Square peg fits into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
		else{&lt;br /&gt;
			System.out.println(&amp;quot;Square peg  does not fit into round hole&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
=== Formal definition ===&lt;br /&gt;
The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations.&lt;br /&gt;
&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53808</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53808"/>
		<updated>2011-10-21T02:32:18Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Implementation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
&lt;br /&gt;
'''1.''' The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
'''2.''' The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
'''3.''' Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
'''4.''' The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
'''5.''' Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53806</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53806"/>
		<updated>2011-10-21T02:30:52Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|center|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53805</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53805"/>
		<updated>2011-10-21T02:30:26Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
[[File:Wiki41.jpg|thumb|left|600x600px|alt=Command Pattern|Figure 1. Working of the Command Pattern.]]&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53794</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53794"/>
		<updated>2011-10-21T02:27:09Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
The adapter pattern, also called wrapper pattern, is used to enable two classes with incompatible interfaces to work together without modifying either class. Adapters are common in real world objects, the most common example being electrical socket adapters which enable electrical appliances from one country to work in another country.&lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
&lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
=== Participants ===&lt;br /&gt;
'''Command'''&lt;br /&gt;
&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
'''Invoker'''&lt;br /&gt;
&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
'''Receiver'''&lt;br /&gt;
&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
'''CommandObject'''&lt;br /&gt;
&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
'''Client'''&lt;br /&gt;
&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Wiki41.jpg&amp;diff=53791</id>
		<title>File:Wiki41.jpg</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Wiki41.jpg&amp;diff=53791"/>
		<updated>2011-10-21T02:25:17Z</updated>

		<summary type="html">&lt;p&gt;Argholka: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53784</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_as&amp;diff=53784"/>
		<updated>2011-10-21T02:16:44Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
==Software Design Patterns==&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for  a class. The singleton also provides a point of global access. &lt;br /&gt;
&lt;br /&gt;
===Common Applications===&lt;br /&gt;
There may be various reasons that necessitate such a requirement for a class.The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc. &lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static Singleton singletonInstance;&lt;br /&gt;
    private Singleton() {  }&lt;br /&gt;
    public static Singleton getInstance() {&lt;br /&gt;
            if (singletonInstance == null) {&lt;br /&gt;
                   singletonInstance = new Singleton();&lt;br /&gt;
            }&lt;br /&gt;
            return singletonInstance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of lazy instantiation where the object is not created until the first time it is required.&lt;br /&gt;
Though the above implementation is straight forward, it does not work in a multi threaded environment. If two threads call the getInstance method at the same time, race conditions may result in more than one instance of the class being created, violating the singleton pattern. This problem can be easily solved by making the 'getInstance' method mutually exclusive using locks. In JAVA this is easily achieved by making the 'getInstance' method synchronized.&lt;br /&gt;
&lt;br /&gt;
Alternatively we could replace &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance; 	          &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
''with''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    private static Singleton singletonInstance = new Singleton();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is an example of eager instantiation and it has a pitfall of wasting memory space if the Singleton object never ends up being used.  However it should also be noted that this version is thread safe because the '''''singletonInstance''''' is created as soon as the Singleton class is loaded by the class loader.&lt;br /&gt;
&lt;br /&gt;
The above examples present a very common way of implementing the singleton pattern. This is by means an exhaustive list of possible implementations. There are additional methods of achieving the same result such as “double checked locking” and using enum data-type&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
Command Pattern focuses on one important aim: To ensure that the object calling a method is completely unaware of how the method is called, implemented and handled. In other words, it aims at achieving decoupling of the caller and the function being called. &lt;br /&gt;
Let us consider a real world example to better understand this pattern. Suppose we have a magical drop-box which has the note “Drop and it will be done”. We will be really happy to just drop of errands like ‘Do my Homework’, ‘Pick up my Laundry’ and many more! The point to consider here is that we are calling an unknown function by dropping errands – unknown to us in terms of implementation details – but with a common crystallized interface – The Drop Box! We as invokers are not concerned about how our homework is done or how our laundry is picked up as long it is done and picked up. We are just concerned to drop off our requests into the Box and let it do the rest.&lt;br /&gt;
This is precisely what Command Pattern achieves. Now the sections below will explain how exactly the pattern goes about achieving this aim.&lt;br /&gt;
&lt;br /&gt;
The command pattern consists of the following parts/participants:&lt;br /&gt;
•	Command&lt;br /&gt;
This is an interface which provides the common function (execute) to the Invoker. Thus, the invoker knows that it can carry out the required action using this execute function. This is the interface where additional operations can be declared so that they are available to the invoker. This is the crystallized interface that was mentioned in the above example. &lt;br /&gt;
&lt;br /&gt;
•	Invoker&lt;br /&gt;
Invoker holds the Command object and when required calls the execute operation of the Command to fulfill the required request.&lt;br /&gt;
&lt;br /&gt;
•	Receiver&lt;br /&gt;
Receiver is the enlightened one and knows the actual logic of carrying out the required function/request. The receiver is the one who will receive the request through the execute function invoked by the invoker. Any class can act as a receiver.&lt;br /&gt;
&lt;br /&gt;
•	CommandObject&lt;br /&gt;
The CommandObject is the one which implements the execute function of the Command interface. The CommandObject or ConcreteCommand binds the execute function and the action of the Receiver to be invoked. Thus, this object is the one who actually calls the required action(s) of the Receiver. &lt;br /&gt;
&lt;br /&gt;
•	Client&lt;br /&gt;
Client creates the required CommandObject and sets its Receiver. Thus, the Client will decide as to which Command will actually be executed. The point to note here is that different commands can have different CommandObjects.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The above diagram gives a gist of how the command pattern works. Here is what happens.&lt;br /&gt;
1.	The Client creates the CommandObject which contains the execute function from the Command interface. The CommandObject provides a specific implementation to the execute function in such a way that it binds a set of receiver actions to the execute function in this CommandObject. This execute can be used to invoke the encapsulated actions of the receiver at any time.&lt;br /&gt;
&lt;br /&gt;
2.	The Client further invokes the set-Command method which passes the CommandObject to the Invoker as an argument thereby saving the CommandObject reference within the Invoker. Thus, the CommandObject is now stored in the Invoker for any further use. This Object can be used by the Invoker to call the actions on the Receiver whenever the Client asks for it.&lt;br /&gt;
&lt;br /&gt;
3.	Now, the Client decides to ask the Invoker to execute the command. Note that the command can stay in the Invoker as long as required and as long as it is not replaced by a different command. Thus, it can be kept or discarded at any point of time.&lt;br /&gt;
&lt;br /&gt;
4.	The Invoker calls the CommandObject’s execute method. Note that the invoker only knows about the execute method at this point of time and nothing else. This ensures decoupling between the invoker object and the receiver object.&lt;br /&gt;
&lt;br /&gt;
5.	Once the invoker calls execute, the execute function in the CommandObject is executed which in turn contains encapsulated methods of the Receiver Object. These methods are called and the operation is completed. Note here that the CommandObject should hold a reference to the Receiver class for it to actually have the ability to call Receiver’s functions. This setting is controlled and done by the Client.&lt;br /&gt;
&lt;br /&gt;
Formal Definition of Command Pattern&lt;br /&gt;
The Command Pattern encapsulates a request as an object and thereby allows us to parameterize other objects with different requests, queue or log requests and support undoable operations. [should have link to the Book or Wikipedia]&lt;br /&gt;
&lt;br /&gt;
Pros and Cons&lt;br /&gt;
1.	The Command Pattern successfully decouples the object which invokes the operation from the object which actually performs the operation.&lt;br /&gt;
2.	CommandObjects are like normal first-class objects. They can be easily extended, manipulated and handled like every other object.&lt;br /&gt;
3.	The Command pattern can easily handle an undo operation. By maintaining a history of the commands executed, we can undo the last operations in the order that they were performed. &lt;br /&gt;
4.	The Command pattern lets us create a group of operations to be performed in one call of execute. This functionality is called as MacroOperations or Composite Commands. Such commands consist of multiple actions related to different Receivers which can be performed one after the other on just one invocation.&lt;br /&gt;
5.	Due to the excellent structure of the Command pattern, it is easily extensible and hence it is easy to declare and add new Commands.&lt;br /&gt;
&lt;br /&gt;
Implementation through Example:&lt;br /&gt;
&lt;br /&gt;
public class Homework {&lt;br /&gt;
	public void doHomework(){&lt;br /&gt;
		System.out.println(&amp;quot;Homework is done.&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public interface Command {&lt;br /&gt;
	public void execute();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class HomeworkCommand implements Command {&lt;br /&gt;
	Homework homework;&lt;br /&gt;
	public setHomework(Homework homework){&lt;br /&gt;
		this.homework = homework;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void execute(){&lt;br /&gt;
		homework.doHomework();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class Invoker {&lt;br /&gt;
	Command command;  			// Command is referenced by the common interface.&lt;br /&gt;
	public void setCommand(Command command){&lt;br /&gt;
		this.command = command;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void performAction(){&lt;br /&gt;
		command.execute();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class Client {&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		Homework homework;&lt;br /&gt;
		Invoker invoker;&lt;br /&gt;
		HomeworkCommand hwCommand = new HomeworkCommand();&lt;br /&gt;
		hwCommand.setHomework(homework);	//Set the Receiver&lt;br /&gt;
		invoker.setCommand(hwCommand); // Set Command to Homework. Any other commands can be used.&lt;br /&gt;
		invoker.performAction();		// Will execute Homework's execute.&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Command Pattern in Ruby&lt;br /&gt;
Command Pattern in Ruby can be accomplished by using Procs. Procs are procedures which consist of binding of variables in its scope when it is created. When we call any Proc, it is not necessary for the caller to know the internal details of the Proc or how it is implemented. The caller just has to pass the required arguments and get the output. This ensures the decoupling of the caller from the method. &lt;br /&gt;
Procs make is easy to implement the Command Pattern efficiently in Ruby.&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
==Conclusion==&lt;br /&gt;
==References==&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50743</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50743"/>
		<updated>2011-09-25T22:06:01Z</updated>

		<summary type="html">&lt;p&gt;Argholka: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
&lt;br /&gt;
To make it more lucid, lets take a look at an example:&lt;br /&gt;
 &amp;lt;code&amp;gt;&lt;br /&gt;
 public class Encapsulation{&lt;br /&gt;
   private String name;&lt;br /&gt;
   private String id;&lt;br /&gt;
   private int age;&lt;br /&gt;
   public int getAge(){&lt;br /&gt;
      return age;&lt;br /&gt;
   }&lt;br /&gt;
   public String getName(){&lt;br /&gt;
      return name;&lt;br /&gt;
   }&lt;br /&gt;
   public String getId(){&lt;br /&gt;
      return id;&lt;br /&gt;
   }&lt;br /&gt;
   public void setAge( int newAge){&lt;br /&gt;
      age = newAge;&lt;br /&gt;
   }&lt;br /&gt;
   public void setName(String newName){&lt;br /&gt;
      name = newName;&lt;br /&gt;
   }&lt;br /&gt;
   public void setId( String newId){&lt;br /&gt;
      id = newId;&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
Example of Abstraction:&lt;br /&gt;
 public abstract class Animal {&lt;br /&gt;
  public int no_of_legs;&lt;br /&gt;
  public double weight;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I don't know as I have no type!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
  public void eat(){&lt;br /&gt;
   System.out.println(&amp;quot;Chomp! Chomp!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 public class Lion extends Animal {&lt;br /&gt;
  public int length_of_mane;&lt;br /&gt;
  public boolean isKingOfJungle;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I am A Lion! Roaarrrrr!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Thus, classes are declared as abstract in Java by using the 'abstract' keyword. Use of Abstraction is necessary during design when such parent classes have to be made as the contain a functionality common to all child classes. The [http://en.wikipedia.org/wiki/Abstract_type abstract class] is useless unless it is inherited. An object of an abstract class cannot be made because its 'too' abstract to exist on its own.   &lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
Example for Inheritance:&lt;br /&gt;
 class Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Pig extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Dog extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Elephant extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
Example of Polymorphism:&lt;br /&gt;
 public interface NonVegetarian{}&lt;br /&gt;
 public class Animal{}&lt;br /&gt;
 public class Lion extends Animal implements NonVegetarian{}&lt;br /&gt;
 Lion l = new Lion(); //Creating a new Lion Object&lt;br /&gt;
 Animal a = l;        //Lion is-a Animal. Hence, Animal object reference can refer to Lion&lt;br /&gt;
 NonVegetarian n = l; //Lion is-a NonVegetarain. Hence, NonVegetarian object reference can refer to Lion&lt;br /&gt;
 Object o = l;        //Lion is-a Object (root of the Class Hierarchy). Hence, Object's object reference can refer to Lion&lt;br /&gt;
Thus, The type of the reference variable would determine the methods that it can invoke on the object.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations &lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows organizing our code into [http://en.wikipedia.org/wiki/Packages_in_Java packages]. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. Task-centric here means that the prime focus is on development of functions which manipulate data and pass them on to other functions or as they are called: modules. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The article has successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50738</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50738"/>
		<updated>2011-09-25T22:02:05Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Comparison in a Nutshell */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
== Important Aspects of Block-Structured Languages ==&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
&lt;br /&gt;
To make it more lucid, lets take a look at an example:&lt;br /&gt;
 &amp;lt;code&amp;gt;&lt;br /&gt;
 public class Encapsulation{&lt;br /&gt;
   private String name;&lt;br /&gt;
   private String id;&lt;br /&gt;
   private int age;&lt;br /&gt;
   public int getAge(){&lt;br /&gt;
      return age;&lt;br /&gt;
   }&lt;br /&gt;
   public String getName(){&lt;br /&gt;
      return name;&lt;br /&gt;
   }&lt;br /&gt;
   public String getId(){&lt;br /&gt;
      return id;&lt;br /&gt;
   }&lt;br /&gt;
   public void setAge( int newAge){&lt;br /&gt;
      age = newAge;&lt;br /&gt;
   }&lt;br /&gt;
   public void setName(String newName){&lt;br /&gt;
      name = newName;&lt;br /&gt;
   }&lt;br /&gt;
   public void setId( String newId){&lt;br /&gt;
      id = newId;&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
Example of Abstraction:&lt;br /&gt;
 public abstract class Animal {&lt;br /&gt;
  public int no_of_legs;&lt;br /&gt;
  public double weight;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I don't know as I have no type!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
  public void eat(){&lt;br /&gt;
   System.out.println(&amp;quot;Chomp! Chomp!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 public class Lion extends Animal {&lt;br /&gt;
  public int length_of_mane;&lt;br /&gt;
  public boolean isKingOfJungle;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I am A Lion! Roaarrrrr!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Thus, classes are declared as abstract in Java by using the 'abstract' keyword. Use of Abstraction is necessary during design when such parent classes have to be made as the contain a functionality common to all child classes. The [http://en.wikipedia.org/wiki/Abstract_type abstract class] is useless unless it is inherited. An object of an abstract class cannot be made because its 'too' abstract to exist on its own.   &lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
Example for Inheritance:&lt;br /&gt;
 class Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Pig extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Dog extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Elephant extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
Example of Polymorphism:&lt;br /&gt;
 public interface NonVegetarian{}&lt;br /&gt;
 public class Animal{}&lt;br /&gt;
 public class Lion extends Animal implements NonVegetarian{}&lt;br /&gt;
 Lion l = new Lion(); //Creating a new Lion Object&lt;br /&gt;
 Animal a = l;        //Lion is-a Animal. Hence, Animal object reference can refer to Lion&lt;br /&gt;
 NonVegetarian n = l; //Lion is-a NonVegetarain. Hence, NonVegetarian object reference can refer to Lion&lt;br /&gt;
 Object o = l;        //Lion is-a Object (root of the Class Hierarchy). Hence, Object's object reference can refer to Lion&lt;br /&gt;
Thus, The type of the reference variable would determine the methods that it can invoke on the object.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations &lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows organizing our code into [http://en.wikipedia.org/wiki/Packages_in_Java packages]. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. Task-centric here means that the prime focus is on development of functions which manipulate data and pass them on to other functions or as they are called: modules. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The article has successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50730</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50730"/>
		<updated>2011-09-25T21:56:57Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Block-structure in Object-Oriented Programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
== Important Aspects of Block-Structured Languages ==&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
&lt;br /&gt;
To make it more lucid, lets take a look at an example:&lt;br /&gt;
 &amp;lt;code&amp;gt;&lt;br /&gt;
 public class Encapsulation{&lt;br /&gt;
   private String name;&lt;br /&gt;
   private String id;&lt;br /&gt;
   private int age;&lt;br /&gt;
   public int getAge(){&lt;br /&gt;
      return age;&lt;br /&gt;
   }&lt;br /&gt;
   public String getName(){&lt;br /&gt;
      return name;&lt;br /&gt;
   }&lt;br /&gt;
   public String getId(){&lt;br /&gt;
      return id;&lt;br /&gt;
   }&lt;br /&gt;
   public void setAge( int newAge){&lt;br /&gt;
      age = newAge;&lt;br /&gt;
   }&lt;br /&gt;
   public void setName(String newName){&lt;br /&gt;
      name = newName;&lt;br /&gt;
   }&lt;br /&gt;
   public void setId( String newId){&lt;br /&gt;
      id = newId;&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
Example of Abstraction:&lt;br /&gt;
 public abstract class Animal {&lt;br /&gt;
  public int no_of_legs;&lt;br /&gt;
  public double weight;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I don't know as I have no type!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
  public void eat(){&lt;br /&gt;
   System.out.println(&amp;quot;Chomp! Chomp!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 public class Lion extends Animal {&lt;br /&gt;
  public int length_of_mane;&lt;br /&gt;
  public boolean isKingOfJungle;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I am A Lion! Roaarrrrr!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Thus, classes are declared as abstract in Java by using the 'abstract' keyword. Use of Abstraction is necessary during design when such parent classes have to be made as the contain a functionality common to all child classes. The [http://en.wikipedia.org/wiki/Abstract_type abstract class] is useless unless it is inherited. An object of an abstract class cannot be made because its 'too' abstract to exist on its own.   &lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
Example for Inheritance:&lt;br /&gt;
 class Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Pig extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Dog extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Elephant extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
Example of Polymorphism:&lt;br /&gt;
 public interface NonVegetarian{}&lt;br /&gt;
 public class Animal{}&lt;br /&gt;
 public class Lion extends Animal implements NonVegetarian{}&lt;br /&gt;
 Lion l = new Lion(); //Creating a new Lion Object&lt;br /&gt;
 Animal a = l;        //Lion is-a Animal. Hence, Animal object reference can refer to Lion&lt;br /&gt;
 NonVegetarian n = l; //Lion is-a NonVegetarain. Hence, NonVegetarian object reference can refer to Lion&lt;br /&gt;
 Object o = l;        //Lion is-a Object (root of the Class Hierarchy). Hence, Object's object reference can refer to Lion&lt;br /&gt;
Thus, The type of the reference variable would determine the methods that it can invoke on the object.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations &lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows organizing our code into [http://en.wikipedia.org/wiki/Packages_in_Java packages]. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The article has successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50717</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50717"/>
		<updated>2011-09-25T21:49:55Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Object-Oriented Terms and Concepts */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
== Important Aspects of Block-Structured Languages ==&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
&lt;br /&gt;
To make it more lucid, lets take a look at an example:&lt;br /&gt;
 &amp;lt;code&amp;gt;&lt;br /&gt;
 public class Encapsulation{&lt;br /&gt;
   private String name;&lt;br /&gt;
   private String id;&lt;br /&gt;
   private int age;&lt;br /&gt;
   public int getAge(){&lt;br /&gt;
      return age;&lt;br /&gt;
   }&lt;br /&gt;
   public String getName(){&lt;br /&gt;
      return name;&lt;br /&gt;
   }&lt;br /&gt;
   public String getId(){&lt;br /&gt;
      return id;&lt;br /&gt;
   }&lt;br /&gt;
   public void setAge( int newAge){&lt;br /&gt;
      age = newAge;&lt;br /&gt;
   }&lt;br /&gt;
   public void setName(String newName){&lt;br /&gt;
      name = newName;&lt;br /&gt;
   }&lt;br /&gt;
   public void setId( String newId){&lt;br /&gt;
      id = newId;&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
Example of Abstraction:&lt;br /&gt;
 public abstract class Animal {&lt;br /&gt;
  public int no_of_legs;&lt;br /&gt;
  public double weight;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I don't know as I have no type!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
  public void eat(){&lt;br /&gt;
   System.out.println(&amp;quot;Chomp! Chomp!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 public class Lion extends Animal {&lt;br /&gt;
  public int length_of_mane;&lt;br /&gt;
  public boolean isKingOfJungle;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I am A Lion! Roaarrrrr!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Thus, classes are declared as abstract in Java by using the 'abstract' keyword. Use of Abstraction is necessary during design when such parent classes have to be made as the contain a functionality common to all child classes. The [http://en.wikipedia.org/wiki/Abstract_type abstract class] is useless unless it is inherited. An object of an abstract class cannot be made because its 'too' abstract to exist on its own.   &lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
Example for Inheritance:&lt;br /&gt;
 class Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Pig extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Dog extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Elephant extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
Example of Polymorphism:&lt;br /&gt;
 public interface NonVegetarian{}&lt;br /&gt;
 public class Animal{}&lt;br /&gt;
 public class Lion extends Animal implements NonVegetarian{}&lt;br /&gt;
 Lion l = new Lion(); //Creating a new Lion Object&lt;br /&gt;
 Animal a = l;        //Lion is-a Animal. Hence, Animal object reference can refer to Lion&lt;br /&gt;
 NonVegetarian n = l; //Lion is-a NonVegetarain. Hence, NonVegetarian object reference can refer to Lion&lt;br /&gt;
 Object o = l;        //Lion is-a Object (root of the Class Hierarchy). Hence, Object's object reference can refer to Lion&lt;br /&gt;
Thus, The type of the reference variable would determine the methods that it can invoke on the object.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations &lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows compartmentalizing our code into packages. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The article has successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50711</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50711"/>
		<updated>2011-09-25T21:48:29Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* What makes Object-Oriented Languages better than Block-structured Languages? */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
== Important Aspects of Block-Structured Languages ==&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
&lt;br /&gt;
To make it more lucid, lets take a look at an example:&lt;br /&gt;
 &amp;lt;code&amp;gt;&lt;br /&gt;
 public class Encapsulation{&lt;br /&gt;
   private String name;&lt;br /&gt;
   private String id;&lt;br /&gt;
   private int age;&lt;br /&gt;
   public int getAge(){&lt;br /&gt;
      return age;&lt;br /&gt;
   }&lt;br /&gt;
   public String getName(){&lt;br /&gt;
      return name;&lt;br /&gt;
   }&lt;br /&gt;
   public String getId(){&lt;br /&gt;
      return id;&lt;br /&gt;
   }&lt;br /&gt;
   public void setAge( int newAge){&lt;br /&gt;
      age = newAge;&lt;br /&gt;
   }&lt;br /&gt;
   public void setName(String newName){&lt;br /&gt;
      name = newName;&lt;br /&gt;
   }&lt;br /&gt;
   public void setId( String newId){&lt;br /&gt;
      id = newId;&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
Example of Abstraction:&lt;br /&gt;
 public abstract class Animal {&lt;br /&gt;
  public int no_of_legs;&lt;br /&gt;
  public double weight;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I don't know as I have no type!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
  public void eat(){&lt;br /&gt;
   System.out.println(&amp;quot;Chomp! Chomp!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 public class Lion extends Animal {&lt;br /&gt;
  public int length_of_mane;&lt;br /&gt;
  public boolean isKingOfJungle;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I am A Lion! Roaarrrrr!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Thus, classes are declared as abstract in Java by using the 'abstract' keyword. Use of Abstraction is necessary during design when such parent classes have to be made as the contain a functionality common to all child classes. The abstract class is useless unless it is inherited. An object of an abstract class cannot be made because its 'too' abstract to exist on its own.   &lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
Example for Inheritance:&lt;br /&gt;
 class Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Pig extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Dog extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Elephant extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
Example of Polymorphism:&lt;br /&gt;
 public interface NonVegetarian{}&lt;br /&gt;
 public class Animal{}&lt;br /&gt;
 public class Lion extends Animal implements NonVegetarian{}&lt;br /&gt;
 Lion l = new Lion(); //Creating a new Lion Object&lt;br /&gt;
 Animal a = l;        //Lion is-a Animal. Hence, Animal object reference can refer to Lion&lt;br /&gt;
 NonVegetarian n = l; //Lion is-a NonVegetarain. Hence, NonVegetarian object reference can refer to Lion&lt;br /&gt;
 Object o = l;        //Lion is-a Object (root of the Class Hierarchy). Hence, Object's object reference can refer to Lion&lt;br /&gt;
Thus, The type of the reference variable would determine the methods that it can invoke on the object.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations &lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows compartmentalizing our code into packages. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The article has successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50709</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50709"/>
		<updated>2011-09-25T21:46:20Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Limitations of Object-Oriented Languages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
== Important Aspects of Block-Structured Languages ==&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
&lt;br /&gt;
To make it more lucid, lets take a look at an example:&lt;br /&gt;
 &amp;lt;code&amp;gt;&lt;br /&gt;
 public class Encapsulation{&lt;br /&gt;
   private String name;&lt;br /&gt;
   private String id;&lt;br /&gt;
   private int age;&lt;br /&gt;
   public int getAge(){&lt;br /&gt;
      return age;&lt;br /&gt;
   }&lt;br /&gt;
   public String getName(){&lt;br /&gt;
      return name;&lt;br /&gt;
   }&lt;br /&gt;
   public String getId(){&lt;br /&gt;
      return id;&lt;br /&gt;
   }&lt;br /&gt;
   public void setAge( int newAge){&lt;br /&gt;
      age = newAge;&lt;br /&gt;
   }&lt;br /&gt;
   public void setName(String newName){&lt;br /&gt;
      name = newName;&lt;br /&gt;
   }&lt;br /&gt;
   public void setId( String newId){&lt;br /&gt;
      id = newId;&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
Example of Abstraction:&lt;br /&gt;
 public abstract class Animal {&lt;br /&gt;
  public int no_of_legs;&lt;br /&gt;
  public double weight;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I don't know as I have no type!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
  public void eat(){&lt;br /&gt;
   System.out.println(&amp;quot;Chomp! Chomp!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 public class Lion extends Animal {&lt;br /&gt;
  public int length_of_mane;&lt;br /&gt;
  public boolean isKingOfJungle;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I am A Lion! Roaarrrrr!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Thus, classes are declared as abstract in Java by using the 'abstract' keyword. Use of Abstraction is necessary during design when such parent classes have to be made as the contain a functionality common to all child classes. The abstract class is useless unless it is inherited. An object of an abstract class cannot be made because its 'too' abstract to exist on its own.   &lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
Example for Inheritance:&lt;br /&gt;
 class Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Pig extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Dog extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Elephant extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
Example of Polymorphism:&lt;br /&gt;
 public interface NonVegetarian{}&lt;br /&gt;
 public class Animal{}&lt;br /&gt;
 public class Lion extends Animal implements NonVegetarian{}&lt;br /&gt;
 Lion l = new Lion(); //Creating a new Lion Object&lt;br /&gt;
 Animal a = l;        //Lion is-a Animal. Hence, Animal object reference can refer to Lion&lt;br /&gt;
 NonVegetarian n = l; //Lion is-a NonVegetarain. Hence, NonVegetarian object reference can refer to Lion&lt;br /&gt;
 Object o = l;        //Lion is-a Object (root of the Class Hierarchy). Hence, Object's object reference can refer to Lion&lt;br /&gt;
Thus, The type of the reference variable would determine the methods that it can invoke on the object.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJfHVd8]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJfHVd8]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations &lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows compartmentalizing our code into packages. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The article has successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50708</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50708"/>
		<updated>2011-09-25T21:45:37Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Object-Oriented Terms and Concepts */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
== Important Aspects of Block-Structured Languages ==&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
&lt;br /&gt;
To make it more lucid, lets take a look at an example:&lt;br /&gt;
 &amp;lt;code&amp;gt;&lt;br /&gt;
 public class Encapsulation{&lt;br /&gt;
   private String name;&lt;br /&gt;
   private String id;&lt;br /&gt;
   private int age;&lt;br /&gt;
   public int getAge(){&lt;br /&gt;
      return age;&lt;br /&gt;
   }&lt;br /&gt;
   public String getName(){&lt;br /&gt;
      return name;&lt;br /&gt;
   }&lt;br /&gt;
   public String getId(){&lt;br /&gt;
      return id;&lt;br /&gt;
   }&lt;br /&gt;
   public void setAge( int newAge){&lt;br /&gt;
      age = newAge;&lt;br /&gt;
   }&lt;br /&gt;
   public void setName(String newName){&lt;br /&gt;
      name = newName;&lt;br /&gt;
   }&lt;br /&gt;
   public void setId( String newId){&lt;br /&gt;
      id = newId;&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
Example of Abstraction:&lt;br /&gt;
 public abstract class Animal {&lt;br /&gt;
  public int no_of_legs;&lt;br /&gt;
  public double weight;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I don't know as I have no type!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
  public void eat(){&lt;br /&gt;
   System.out.println(&amp;quot;Chomp! Chomp!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 public class Lion extends Animal {&lt;br /&gt;
  public int length_of_mane;&lt;br /&gt;
  public boolean isKingOfJungle;&lt;br /&gt;
  public void makeSound(){&lt;br /&gt;
   System.out.println(&amp;quot;I am A Lion! Roaarrrrr!&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Thus, classes are declared as abstract in Java by using the 'abstract' keyword. Use of Abstraction is necessary during design when such parent classes have to be made as the contain a functionality common to all child classes. The abstract class is useless unless it is inherited. An object of an abstract class cannot be made because its 'too' abstract to exist on its own.   &lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
Example for Inheritance:&lt;br /&gt;
 class Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Pig extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Dog extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
 class Elephant extends Animal {&lt;br /&gt;
   ..........&lt;br /&gt;
 }&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
Example of Polymorphism:&lt;br /&gt;
 public interface NonVegetarian{}&lt;br /&gt;
 public class Animal{}&lt;br /&gt;
 public class Lion extends Animal implements NonVegetarian{}&lt;br /&gt;
 Lion l = new Lion(); //Creating a new Lion Object&lt;br /&gt;
 Animal a = l;        //Lion is-a Animal. Hence, Animal object reference can refer to Lion&lt;br /&gt;
 NonVegetarian n = l; //Lion is-a NonVegetarain. Hence, NonVegetarian object reference can refer to Lion&lt;br /&gt;
 Object o = l;        //Lion is-a Object (root of the Class Hierarchy). Hence, Object's object reference can refer to Lion&lt;br /&gt;
Thus, The type of the reference variable would determine the methods that it can invoke on the object.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJfHVd8]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJfHVd8]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJoO7qg]&lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.[http://stackoverflow.com/questions/2853316/disadvantage-of-oop]&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows compartmentalizing our code into packages. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The article has successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50688</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50688"/>
		<updated>2011-09-25T21:21:39Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
== Important Aspects of Block-Structured Languages ==&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJfHVd8]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJfHVd8]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJoO7qg]&lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.[http://stackoverflow.com/questions/2853316/disadvantage-of-oop]&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows compartmentalizing our code into packages. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The article has successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50687</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1e aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1e_aa&amp;diff=50687"/>
		<updated>2011-09-25T21:21:18Z</updated>

		<summary type="html">&lt;p&gt;Argholka: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1e aa&lt;br /&gt;
&lt;br /&gt;
''Block-Structured languages vs Object-Oriented languages; effectiveness of Object-Oriented languages and use of block-structure in Object-Oriented languages.''&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== Brief Background on the Programming Paradigms ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigms] form the fundamental basis of the style in which we code. Paradigms define the way the code is structured aesthetically. Different paradigms differ in the way in which a language defines its concepts about the way to represent the code elements i.e. variables, functions, objects etc. and the way in which computation of the code takes place. Thus, any paradigm acts as a ''structure or set of rules'' on which that language is based. This provides the programmer with set of principles which are to be obeyed when the language is used.&lt;br /&gt;
&lt;br /&gt;
There are many different programming paradigms which are developed over the years. Each one offers something different than the others and many are considered much better over the others. Another flavour to paradigms is that some languages can support more than one paradigms. This gives the programmer the choice of how to use the elements of different paradigms in his own discretion. &lt;br /&gt;
&lt;br /&gt;
In this article, we focus on two programming paradigms: Block-Structured programming and Object-Oriented Programming.&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
This Wiki chapter talks about the basic fundamentals of two programming paradigms; [http://en.wikipedia.org/wiki/Block_(programming) block structured] programming and [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented programming] and explains the advantages of Object Oriented programming over block structured programming which made O-O languages more common and widely used in the Software Industry today. We also focus on the practicability of using block structured approach in O-O languages.&lt;br /&gt;
&lt;br /&gt;
==Block-Structured Languages==&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Block_(programming) Block] is a part of code that is clustered together. It is thus; a group of program statements and variables referred to in those statements. Block of code always begins with variable declarations and is followed by procedural declarations, is always contained within delimiters; typically ''begin-end'', ''opening and closing curly braces'' '{ }' and can be compiled and executed as a single execution unit. Block can be the body of a subroutine, a function or an entire program. The main block can contain subsections consisting of inner blocks. Those inner blocks can contain more inner blocks giving rise to a nested block structure. Typically, Nesting can be repeated to any depth required. One example of a language which allows such block structure is [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal][http://stratadoc.stratus.com/vos/15.1.1/r014-01/wwhelp/wwhimpl/common/html/wwhelp.htm?context=r014-01&amp;amp;file=ch1r014-01m.html].&lt;br /&gt;
&lt;br /&gt;
 program a;  &lt;br /&gt;
    var id1, id2, id3 : integer;     { program a declarations }  &lt;br /&gt;
                                                   &lt;br /&gt;
    procedure b;                            &lt;br /&gt;
          var id1 : integer;         { procedure b declarations } &lt;br /&gt;
                                                         &lt;br /&gt;
        procedure c;                         &lt;br /&gt;
               var id2 : integer;    { procedure c declarations}      &lt;br /&gt;
               begin    { Beginning of c's statement part }             &lt;br /&gt;
               id2 := id1;                     &lt;br /&gt;
               end;              &lt;br /&gt;
          begin     { Beginning of b's statement part }&lt;br /&gt;
          id1 := id3;                           &lt;br /&gt;
          id2 := id1;&lt;br /&gt;
          end; &lt;br /&gt;
                                                                       &lt;br /&gt;
     begin     { Beginning of main program's statement part } &lt;br /&gt;
     id1 := id2; &lt;br /&gt;
     end.&lt;br /&gt;
&lt;br /&gt;
In most primitive block structured languages, the scope of a variable can be limited to the block in which it is declared. This is called [http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping '''lexical scoping''']. Thus, referring to the nested structure of the blocks; all the variables declared in the outer block can be accessed within that block and all of its inner blocks but are not accessible outside that block. Additionally, values of the variables in the outer blocks are accessible in the inner blocks if and only if there is no other variable in the inner block with the same name. This duplicate declaration of variables is called [http://en.wikipedia.org/wiki/Variable_shadowing '''Shadowing''']. &lt;br /&gt;
&lt;br /&gt;
By having statements grouped together as a Block allows us to treat it as a single statement and thus allows the programmer to keep the 'lexical' scope of the functions, variables and procedures closely bound to that Block. Earliest block-structured languages were Algol 58 and Algol 60 with which the initial idea of block was born.&lt;br /&gt;
&lt;br /&gt;
== Important Aspects of Block-Structured Languages ==&lt;br /&gt;
=== Relation of Block-Structured Programming to Structured Programming ===&lt;br /&gt;
There is a subtle relation between block programming and structured programming. Structured programming encompasses majority of the fundamentals of block programming paradigm. Most of the block-structured languages fall under the structured programming paradigm for example: Algol, Pascal. In essence, structured programming employs a hierarchical approach in which the main problem is broken down into different smaller modules. Thus, it breaks down a bigger task into smaller ones and therefore solving the smaller tasks leads to indirectly solving the actual problem. &lt;br /&gt;
&lt;br /&gt;
The important thing to note here is that such programs always have a single point of entry and often have single points of exit. The modules in this paradigm are independent of each other and thus; are blocks of code where the ''scope is limited'' to that particular module. Structured Programming normally imply simple hierarchical flow structures consisting of ''sequence'' (execution of statements in particular order), ''selection'' (some selection criteria) and ''iteration'' (repetition until the program reaches a certain state).&lt;br /&gt;
&lt;br /&gt;
=== Features of Block-Structured Languages ===&lt;br /&gt;
*Structured programming is task-centric&lt;br /&gt;
*Applies a [http://en.wikipedia.org/wiki/Top-down_design top-down approach] of problem solving.&lt;br /&gt;
*It is a straight forward programming approach with a pre-defined flow.&lt;br /&gt;
*Programs have a modular design structure.&lt;br /&gt;
*Employs an approach of bringing data which is to be operated upon to the functions or methods.&lt;br /&gt;
*Most often; such programs have a single point of entry and single point of exit.&lt;br /&gt;
*Allows the programmer to keep the program within his intellectual grasp due to its modular design and limited variable scope.&lt;br /&gt;
*Programs have data-structures with a limited scope.&lt;br /&gt;
*Programs allow limited control structures.&lt;br /&gt;
&lt;br /&gt;
=== Advantages of Block-Structured Languages and related programming paradigms ===&lt;br /&gt;
*'''Simplicity in Writing Code:''' It is extremely easy to write code in a block structured language. Modularity is the prime reason due to which programmers can concentrate on various aspects of the program and design their code in the most efficient way. The concept of single point of entry also allows the programmer to better design their code in a heirarchial strucuture and thus create a better solution. Easiness in writing code amounts to saving precious time. If written efficiently, procedures can also be used in other programs requiring the same functionality. &lt;br /&gt;
&lt;br /&gt;
*'''Debugging made easy:''' Modular structure provides the progammer to isolate bugs easily. As each procedure does only one particular task, it is easy to debug individually. Programmer can recognize the errors by simply narrowing it down to the procedure which is faulty. Additionally, each procedure in the modular design has a single point of entry i.e. through any other procedure. This makes it easy to write and use Stubs for testing individual procedures before they are used or integrated into the main program. Stubs are dummy procedures which provide test data to the procedures.&lt;br /&gt;
&lt;br /&gt;
*'''Understandability of Code:''' It is extremely easy to look at procedures and figure out the entire modular structure of the program. Each procedure and variables have meaningful names which makes it very lucid and easy to understand. Morever, the scope of the variables in the procedure is often limited to that procedure itself which adds to the simplicity of figuring what that variable is used for.&lt;br /&gt;
&lt;br /&gt;
*'''Modification made simple:''' Due to all the above properties of a block structured program, any programmer looking at code written by some other programmer can easily understand and thus modify it with least effort. Additionally, if the specifications of the program change later, changes to it can be made easily.&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Block-Structured Languages and related programming paradigm ===&lt;br /&gt;
*Top-down design approach focuses more on the design of sequence of instructions required for the solution. Design of data-structures which is also an integral part of designing the solution to the problem is outside the scope of the top-down design approach. &lt;br /&gt;
*As data is to be passed to the methods; there is no encapsulation. A better approach is keeping data as it is and declaring the necessary funcitons near the data.&lt;br /&gt;
*There is no information hiding concept in structured programming. The concept of lexical scope applies but is not equivalent to information hiding or encapsulation.&lt;br /&gt;
*Top-down design approach does not suit all type of problems. If we cannot determine the sequence of instructions in advance, structured programming cannot be applied for that problem.&lt;br /&gt;
*The modular design of structured programming poses a very big problem. By dividing the problem into seperate methods/functions, it limits the usability of those functions to only that problem or problems of the specific genre. These modules/methods cannot be used easily into other problems. Use of such modules will require serious re-design and effort.&lt;br /&gt;
*Debugging is not simple once the size of the program increases. Programmer has to actively understand the entire structure of the program to debug even a smallest problem as modules in the structure depend on each other.&lt;br /&gt;
&lt;br /&gt;
== Object-Oriented Programming ==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm which focuses on '''objects''' ''instead of'' '''actions''' and '''data''' ''instead of'' '''logic'''.&lt;br /&gt;
Historically, a program has always been viewed as a logical sequence of instructions that takes the input, processes it, and produces the output. Due to this focus, the programming challenge has always been the logical sequence, rather than defining data. Whereas, OOP takes the focus away from the procedure. It represents data from the real world (called as objects) which we really want to manipulate rather than the logic required to manipulate them.&lt;br /&gt;
&lt;br /&gt;
While Simula was the first object-oriented programming language, the most popular OOP languages used today are  Java, Python, C++, Visual Basic .NET and Ruby. Although many languages claim to be solely object oriented, most of the time that is not the case. There are some languages that are purely o-o ,while others are hybrid. Now, a language must capture several qualities for it to be purely O-O. These qualities are:&lt;br /&gt;
*Encapsulation/Information Hiding&lt;br /&gt;
*Inheritance&lt;br /&gt;
*Polymorphism/Dynamic Binding&lt;br /&gt;
*All pre-defined types are Objects&lt;br /&gt;
*All operations performed by sending messages to Objects&lt;br /&gt;
*All user-defined types are Objects&lt;br /&gt;
&lt;br /&gt;
Below is an small example of Object-Oriented Programming in Java:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
  int x;&lt;br /&gt;
  int y;&lt;br /&gt;
  int get(int p, int q){&lt;br /&gt;
  x=p; y=q; return(0);&lt;br /&gt;
  }&lt;br /&gt;
  void Show(){&lt;br /&gt;
  System.out.println(x);&lt;br /&gt;
  }&lt;br /&gt;
 }  // end of Class A    &lt;br /&gt;
        &lt;br /&gt;
 class B extends A{&lt;br /&gt;
  public static void main(String args[]){&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.get(5,6);&lt;br /&gt;
  a.Show();&lt;br /&gt;
  }&lt;br /&gt;
  void display(){&lt;br /&gt;
  System.out.println(&amp;quot;B&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 } // end of Class B&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
''Pure'' O-O languages satisfy all the above qualities, whereas, ''hybrid'' languages support some of these. Typically, many languages support first three qualities, but not the last three. Some examples of pure O-O languages are Eiffel, Smalltalk, and Ruby.&lt;br /&gt;
&lt;br /&gt;
Many think of Java as a pure Object-Oriented language, but by its inclusion of &amp;quot;basic&amp;quot; types that are not objects, it fails to meet the fourth quality. Also it fails to meet quality five by implementing basic arithmetic as built-in operators, rather than messages to objects. [http://en.wikipedia.org/wiki/C++_(programming_language) C++] supports multiple paradigms, O-O being one of them. Thus it is not a pure oo language. Another seemingly object oriented language, Python is actually a multi-paradigm supporting language. At times, o-o concepts seem to be fixed up in it.  Some operations are implemented as methods, while others are implemented as global functions. The ''self'' parameter adds to its awkwardness. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby] on the other hand, is a scripting language which was created as a reaction to [http://en.wikipedia.org/wiki/Python_(programming_language) Python] and [http://en.wikipedia.org/wiki/Perl_(programming_language) Perl]. The designers of Ruby wanted a language that was stronger than Perl and more object oriented than Python. Visual Basic and Perl are both procedural languages that have had some Object-Oriented support added on as the languages have matured.&lt;br /&gt;
&lt;br /&gt;
=== Features of Object-Oriented Languages ===&lt;br /&gt;
==== Object-Oriented Terms and Concepts ====&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]'''&lt;br /&gt;
In OOP the encapsulation is mainly achieved by including within a program object all the resources needed for the object to function i.e. methods and data.  Due to this, a class may  change its internal implementation without affecting the overall functioning of the system.&lt;br /&gt;
Thus encapsulation hides what a class and makes it a black box. Interfaces are used to interact with the objects and hide the implementation of the object.&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Abstraction Abstraction]'''&lt;br /&gt;
Abstraction is suppressing the implementation details while representing the data by focusing on the idea, qualities and properties. Abstraction makes concentrating on the concepts easier by factoring out the details. It is the primary means of managing complexity in large programs.&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]'''&lt;br /&gt;
Deriving a new class from an existing one by simply extending the parent class is called as inheritance. The extended class is called as a subclass and it inherits attributes and behaviors of its parent class which is also called as superclass or base class.&lt;br /&gt;
*'''[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]'''&lt;br /&gt;
The dictionary meaning of polymorphism is “many shapes”. In OOP, it is the ability of an interface to be realized in multiple ways. In OOP the polymorphism is achieved by using many different techniques named method overloading, operator overloading and method overriding.&lt;br /&gt;
&lt;br /&gt;
''Method overloading'' : The method overloading is the ability to define several methods all with the same name but different signatures.&lt;br /&gt;
&lt;br /&gt;
''Operator overloading'' : The operator overloading is a property in which all the operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. &lt;br /&gt;
&lt;br /&gt;
''Method overriding'' : Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.&lt;br /&gt;
&lt;br /&gt;
=== What makes Object-Oriented Languages better than Block-structured Languages? ===&lt;br /&gt;
What block-structured programming does for legacy systems, object-oriented programming does for software systems in general. That is, it manages the complexity of these systems. But object- oriented technology has better things to offer. Here is how:&lt;br /&gt;
*The '''program structure is simplified''' as the real world objects have been modeled in the software objects. This makes designing the problem much more simple that block structured programming where procedures have to be written for every functionality needed. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*The''' program becomes modular''' as the internal working of each object is highly decoupled from other parts of the program which is not the case in block structured programming where modules depend on one another as compared to O-O programming. [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Debugging and testing''' becomes an easy job in O-O Programming. Unit tests can be written for each class and thus its objects and they can be tested exhaustively. Also making minor changes in data representation or procedures is simple and does not affect any other component of the code. This makes the code maintainable as well as modifiable. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and their Objects can be thought of self-contained as they contain data and functions that act on data tied together. Thus, using these classes and thus objects in another program where the same functionality is needed is possible. It is also''' possible to extend''' the functions provided by the class easily. '''Reuse of code''' in new applications becomes easy. [http://wiki.tcl.tk/13398]&lt;br /&gt;
*Classes and Objects provide''' data security''' through the principles of encapsulation and access specifiers. Thus, objects can contain data which is available to the outside world and data which is completely controlled by itself. Object provides interfaces to access this data whose implementation is not available to other parts of the program. Data security is not provided by block structured programming where only scope rules apply.&lt;br /&gt;
*As compared to structured programming, OOP is '''more scalable.''' An object’s interface may guide you to reuse the code in new software, besides providing you with the information that needs to be replaced without affecting other code. Thus, newer technology can replace the aging code hassle free.&lt;br /&gt;
*Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; making the code '''easily extensible'''. This requires considerable effort in Block-structured programming where adding new features can result into dependency problems with other existing modules.   [http://eprints.ecs.soton.ac.uk/857/3/html/node3.html]&lt;br /&gt;
*'''Real world modeling''' is possible using Object-oriented system in a more complete fashion as compared to traditional methods. Organizing objects and methods into classes is what makes it easier to reflect the real world. This makes it possible to visualize the problem easily and practically.&lt;br /&gt;
*The modular structure for programs in O-O Programming makes it possible for '''defining abstract data-types''' according to ''required specifications'' where implementation details are hidden and the unit has a clearly defined interface. This is not possible in Block structured programming. [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJfHVd8]&lt;br /&gt;
*OOP provides a '''good frameworks''' for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing scalable applications. This facility is not available in Block-structured programming. [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJfHVd8]&lt;br /&gt;
*Some other advantages of OOP are that it makes'' code development faster, has better IDEs, allows single-instance code, testability, Catch errors at compile time rather than at run-time.''&lt;br /&gt;
&lt;br /&gt;
=== Limitations of Object-Oriented Languages ===&lt;br /&gt;
*It is not always that the real world neatly divides into classes and subclasses. There may arise some ambiguity as the complexity increases. This may lead to artificial class relations [http://wiki.answers.com/Q/Benefits_of_object_oriented_programming#ixzz1XFJoO7qg]&lt;br /&gt;
*O-O programs is sometimes hard to test, especially in case of classes with low cohesion.[http://stackoverflow.com/questions/2853316/disadvantage-of-oop]&lt;br /&gt;
*As the complexity of the problem increases, unnecessary complications  in the program structure may be introduced making it difficult to interpret.&lt;br /&gt;
&lt;br /&gt;
== Block-structure in Object-Oriented Programming ==&lt;br /&gt;
The fundamentals of a Block-structure cannot be eradicated from modern programming. O-O languages such as Java encompass block structure in the declaration of methods, functions and procedures. The Object-Oriented properties of such languages make them not-block structured. &lt;br /&gt;
&lt;br /&gt;
Java has all the features of an Object-Oriented language but makes use of block structures in writing looping constructs such as 'if-else', 'while', 'for'. The functions written in Java also make use of the lexical scope rules. This means that when we write a function in Java, the local variables declared within the function block are known to that particular function only. Thus, this is logically equivalent to the functions in block-structured languages such as C. Java also contains the concept of global variables which are accessible throughout the program to all classes.&lt;br /&gt;
&lt;br /&gt;
Example of local variables is shown below. These variables are only available when the function is called using an object of the Class type Structure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 class Structure&lt;br /&gt;
 {&lt;br /&gt;
   private int a;&lt;br /&gt;
   private int b;&lt;br /&gt;
   public void isItAStructure(boolean t) {&lt;br /&gt;
     int local_variable1;&lt;br /&gt;
     int local_variable2;&lt;br /&gt;
     ..........&lt;br /&gt;
      }&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://download.oracle.com/javase/tutorial/java/javaOO/nested.html Nested classes] are also supported in Java. Thus, we can have class declared under a class. There are two types of nested classes; non-static( which are called inner classes ) and static. Scoping rules apply for nested classes. The inner class instance can access the variables and methods of the enclosing class even if declared private. Additionally, this inner class instance can only exist if there is a corresponding outer class instance. This is an efficient way of increasing encapsulation.&lt;br /&gt;
&lt;br /&gt;
Example of nested classes is shown below.[http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 public class OuterClass&lt;br /&gt;
 {&lt;br /&gt;
   private String outerInstanceVar;&lt;br /&gt;
   public class InnerClass&lt;br /&gt;
   {&lt;br /&gt;
      public void printVars()&lt;br /&gt;
      {&lt;br /&gt;
         System.out.println( &amp;quot;Print Outer Class Instance Var.:&amp;quot; + outerInstanceVar);&lt;br /&gt;
      }&lt;br /&gt;
   } &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Java also allows compartmentalizing our code into packages. Packages also have scoping rules. Classes declared in one package cannot be accessed outside that package unless the package is explicitly imported into the program. This can be thought of logically as being one block of code(consisting of multiple files) which has scoping restrictions.&lt;br /&gt;
Thus, block-structure can be used and is used in some of today's O-O languages.&lt;br /&gt;
&lt;br /&gt;
== Comparison in a Nutshell ==&lt;br /&gt;
Let us compare both the programming paradigms with respect to different points which brings out a strong distinction between the two.&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Point of Comparison &lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Block-Structured Languages&lt;br /&gt;
! scope=&amp;quot;col&amp;quot; | Object-Oriented Languages&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Primary focus  &lt;br /&gt;
|| Focus on finding the''' sequence of instructions''' necessary to solve the problem. Design of the necessary data-structures is out of scope. It is '''task-centric'''. || Focus on identifying and''' representing the problem in terms of an 'object'''' which has its own data, sub-routines and state. Different objects in the problem interact by sending messages to each other and thus result in change in its internal state. The final state and values of the objects refer to the solution. It is '''data-centric'''.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Problem Solving Approach &lt;br /&gt;
|| Primarily''' Top-down''' design || '''Identification and design of necessary objects'''. Close to being 'better models of the way the world works'.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Program Flow &lt;br /&gt;
|| '''Often sequential''' with program having single point of entry and exit. || '''Complex''' program flow. Can sometimes depend on the internal state of the objects.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Modularity &lt;br /&gt;
|| '''Limited modularity'''. Program is divided into modules or per say procedures independent of each other but are constrained due to uniqueness to that particular problem. || '''Extremely modular''' due to the presence of objects which contain their own data and sub-routines.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Data Protection/Hiding &lt;br /&gt;
|| '''No concept of data-hiding'''. Variables local to one method cannot be accessed by other method. But, Global variables can be accessed anywhere within the program. || One of the main fundamentals of O-O languages.''' Access specifiers''' like 'public', 'private' and 'protected' dictate the rules of data-hiding. Data which is private is confined to one object and cannot be directly changed by any other method except its own. This places the responsibility of managing data with the object itself This is called as ownership. Thus, data can be accessed ( read/write/modified )''' only''' through the object's own interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Ease of Understanding &lt;br /&gt;
||''' Smaller programs''' are '''easy to understand''' but as the program increases in size; understanding is a struggle. || '''Easy to understand''' due to its real world-like design and flow. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Reuse of Code &lt;br /&gt;
|| '''Limited or no''' re-usability. ||''' Highly re-usable code''' as the code developed can be easily modified or extended to suit a problem's need.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Support for declaring new data types &lt;br /&gt;
||''' Extremely difficult''' as no in-built functionality exists. || '''Easily possible''' due to the concept of classes. Generic classes can be built as per the required specifications.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Efficiency &lt;br /&gt;
|| '''Efficient''' for solving '''small''' problems. || '''Efficient''' for solving '''large problems''' which have a complex structure and require complex data-types, abstraction and data-security.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Maintenance &lt;br /&gt;
|| Maintenance is''' easy for smaller programs''' but can consume''' a-lot of effort for larger program''' size as it requires the programmer to know and understand the dependencies of every module in the program. This makes it difficult to debug and test the program. ||''' Extremely simple''' as O-O languages aim for high modularity. Secondly, programmer is not concerned with the details of how the data is stored and represented. Thirdly, they also tend to keep low coupling which makes it easy to debug and test different modules in the program.&lt;br /&gt;
|-&lt;br /&gt;
|&lt;br /&gt;
*Extensibility &lt;br /&gt;
|| '''Less Extensible''' as modules developed need to be re-organised and re-structured heavily in order to meet different needs. || '''High extensibility''' is one of the most important advantages of OOP. Code can be easily modified and 'plugged-in' to a different program. Methods can be exteneded due to many properties such as polymorphism, inheritance and support for multiple inheritance through interfaces.&lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Flexibility &lt;br /&gt;
|| '''Less flexible.''' Sometimes, certain problems do not fit into the 'top-down design' approach. || '''High flexibility.''' The modelling of problems into world-like objects makes it easy to solve any practical problem. &lt;br /&gt;
|-&lt;br /&gt;
| &lt;br /&gt;
*Examples &lt;br /&gt;
|| [http://en.wikipedia.org/wiki/C_(programming_language) C], [http://en.wikipedia.org/wiki/Pascal_(programming_language) Pascal], [http://en.wikipedia.org/wiki/ALGOL_58 Algol 58], [http://en.wikipedia.org/wiki/ALGOL_60 Algol 60] || [http://en.wikipedia.org/wiki/C%2B%2B C++], [http://en.wikipedia.org/wiki/Java_(programming_language) Java], [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], [http://en.wikipedia.org/wiki/Python_(programming_language) Python].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We have successfully summarized the advantages and disadvantages of both block-structured and object-oriented programming. Thus, Object-oriented programming is much better than Block-Structured programming in different aspects and offers much more language-features. Object oriented programming provides the user to deal with real world objects and thus makes it more easier for the programmer to deal with large complex problems. Block structured programming provides the users with a structured task-centric approach and some of its basic fundamentals are still used in Object-Oriented languages. With the ever growing need for scalability, modularization, maintainability and re-usability; Object-Oriented programming is going to be preferred paradigm of programmers.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
*In-depth Description of Object-Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming&lt;br /&gt;
*In-depth Description of Block Programming - http://en.wikipedia.org/wiki/Block_(programming)&lt;br /&gt;
*In-depth Description of Structured Programming - http://en.wikipedia.org/wiki/Structured_programming&lt;br /&gt;
*About Simple Procedural and Block Structured, Procedural languages (Article from University of Missouri-Kansas City) - http://v.web.umkc.edu/vm63a/441p2p1.htm&lt;br /&gt;
*Structured vs. Object-Oriented Programming (By Jane Taylor) - http://janeataylor.wordpress.com/2005/12/02/structured-vs-object-oriented-programming/&lt;br /&gt;
*Structured Programming - http://www.wisegeek.com/what-is-structured-programming.htm&lt;br /&gt;
*Characteristics of a structured program by Ned Chapin,Susan P. Denniston - http://portal.acm.org/citation.cfm?id=953398&lt;br /&gt;
*Explanation of Nested Classes - http://download.oracle.com/javase/tutorial/java/javaOO/nested.html&lt;br /&gt;
*Example of Nested Classes - http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes &lt;br /&gt;
*Advantages and Disadvantages of OOP by Larry Smith - http://wiki.tcl.tk/13398 &lt;br /&gt;
*Object Oriented Basic Concepts and Advantages - http://eprints.ecs.soton.ac.uk/857/3/html/node3.html &lt;br /&gt;
*Basic Object-Oriented Concepts by Edward V. Berard (The Object Agency, Inc.) - http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html &lt;br /&gt;
*Introduction to Object Oriented Programming Concepts (OOP) and More - http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx&lt;/div&gt;</summary>
		<author><name>Argholka</name></author>
	</entry>
</feed>