<?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=Psdeshp2</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=Psdeshp2"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Psdeshp2"/>
	<updated>2026-06-23T07:20:33Z</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_2012/ch2a_2w17_pt&amp;diff=68649</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68649"/>
		<updated>2012-10-27T00:42:08Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* UML Class Diagram */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a [http://en.wikipedia.org/wiki/Collaboration collaboration] between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the  [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern], you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==[http://en.wikipedia.org/wiki/Unified_Modeling_Language UML] Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Facade is more like a simple gateway to a complicated set of functionality. You make a black-box for your clients to worry less i.e. make interfaces simpler&lt;br /&gt;
*Where as decorator is used to add more gunpowder to your objects (note the term objects -- you typically decorate objects dynamically at runtime). You do not hide/impair the existing interfaces of the object but simply extend it at runtime.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Composite pattern and Decorator pattern===&lt;br /&gt;
*The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity.&lt;br /&gt;
*The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity&lt;br /&gt;
*Composite pattern: gives an unified interface to a leaf and composite.&lt;br /&gt;
*Decorator: composite gives additional feature to leaf, while giving unified interface.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Software_design_pattern Software design patterns]&lt;br /&gt;
*[http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy Computer science design patterns]&lt;br /&gt;
*[http://www.dofactory.com/Patterns/ Patterns]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern]&lt;br /&gt;
*[http://www.oodesign.com/ O-O design]&lt;br /&gt;
*[http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison Pattern Comparisons ]&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;br /&gt;
*[http://stackoverflow.com/questions/2233952/difference-between-the-composite-pattern-and-decorator-pattern Composite vs Decorator]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68645</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68645"/>
		<updated>2012-10-27T00:41:10Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Design Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a [http://en.wikipedia.org/wiki/Collaboration collaboration] between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the  [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern], you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Facade is more like a simple gateway to a complicated set of functionality. You make a black-box for your clients to worry less i.e. make interfaces simpler&lt;br /&gt;
*Where as decorator is used to add more gunpowder to your objects (note the term objects -- you typically decorate objects dynamically at runtime). You do not hide/impair the existing interfaces of the object but simply extend it at runtime.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Composite pattern and Decorator pattern===&lt;br /&gt;
*The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity.&lt;br /&gt;
*The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity&lt;br /&gt;
*Composite pattern: gives an unified interface to a leaf and composite.&lt;br /&gt;
*Decorator: composite gives additional feature to leaf, while giving unified interface.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Software_design_pattern Software design patterns]&lt;br /&gt;
*[http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy Computer science design patterns]&lt;br /&gt;
*[http://www.dofactory.com/Patterns/ Patterns]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern]&lt;br /&gt;
*[http://www.oodesign.com/ O-O design]&lt;br /&gt;
*[http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison Pattern Comparisons ]&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;br /&gt;
*[http://stackoverflow.com/questions/2233952/difference-between-the-composite-pattern-and-decorator-pattern Composite vs Decorator]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68644</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68644"/>
		<updated>2012-10-27T00:40:46Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Design Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a [http://en.wikipedia.org/wiki/Collaboration collaboration] between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern], you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Facade is more like a simple gateway to a complicated set of functionality. You make a black-box for your clients to worry less i.e. make interfaces simpler&lt;br /&gt;
*Where as decorator is used to add more gunpowder to your objects (note the term objects -- you typically decorate objects dynamically at runtime). You do not hide/impair the existing interfaces of the object but simply extend it at runtime.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Composite pattern and Decorator pattern===&lt;br /&gt;
*The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity.&lt;br /&gt;
*The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity&lt;br /&gt;
*Composite pattern: gives an unified interface to a leaf and composite.&lt;br /&gt;
*Decorator: composite gives additional feature to leaf, while giving unified interface.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Software_design_pattern Software design patterns]&lt;br /&gt;
*[http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy Computer science design patterns]&lt;br /&gt;
*[http://www.dofactory.com/Patterns/ Patterns]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern]&lt;br /&gt;
*[http://www.oodesign.com/ O-O design]&lt;br /&gt;
*[http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison Pattern Comparisons ]&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;br /&gt;
*[http://stackoverflow.com/questions/2233952/difference-between-the-composite-pattern-and-decorator-pattern Composite vs Decorator]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68640</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68640"/>
		<updated>2012-10-27T00:39:25Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Design Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a [http://en.wikipedia.org/wiki/Collaboration collaboration] between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Facade is more like a simple gateway to a complicated set of functionality. You make a black-box for your clients to worry less i.e. make interfaces simpler&lt;br /&gt;
*Where as decorator is used to add more gunpowder to your objects (note the term objects -- you typically decorate objects dynamically at runtime). You do not hide/impair the existing interfaces of the object but simply extend it at runtime.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Composite pattern and Decorator pattern===&lt;br /&gt;
*The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity.&lt;br /&gt;
*The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity&lt;br /&gt;
*Composite pattern: gives an unified interface to a leaf and composite.&lt;br /&gt;
*Decorator: composite gives additional feature to leaf, while giving unified interface.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Software_design_pattern Software design patterns]&lt;br /&gt;
*[http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy Computer science design patterns]&lt;br /&gt;
*[http://www.dofactory.com/Patterns/ Patterns]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern]&lt;br /&gt;
*[http://www.oodesign.com/ O-O design]&lt;br /&gt;
*[http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison Pattern Comparisons ]&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;br /&gt;
*[http://stackoverflow.com/questions/2233952/difference-between-the-composite-pattern-and-decorator-pattern Composite vs Decorator]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68254</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68254"/>
		<updated>2012-10-26T21:05:15Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Facade is more like a simple gateway to a complicated set of functionality. You make a black-box for your clients to worry less i.e. make interfaces simpler&lt;br /&gt;
*Where as decorator is used to add more gunpowder to your objects (note the term objects -- you typically decorate objects dynamically at runtime). You do not hide/impair the existing interfaces of the object but simply extend it at runtime.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Composite pattern and Decorator pattern===&lt;br /&gt;
*The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity.&lt;br /&gt;
*The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity&lt;br /&gt;
*Composite pattern: gives an unified interface to a leaf and composite.&lt;br /&gt;
*Decorator: composite gives additional feature to leaf, while giving unified interface.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Software_design_pattern Software design patterns]&lt;br /&gt;
*[http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy Computer science design patterns]&lt;br /&gt;
*[http://www.dofactory.com/Patterns/ Patterns]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern]&lt;br /&gt;
*[http://www.oodesign.com/ O-O design]&lt;br /&gt;
*[http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison Pattern Comparisons ]&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;br /&gt;
*[http://stackoverflow.com/questions/2233952/difference-between-the-composite-pattern-and-decorator-pattern Composite vs Decorator]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68251</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68251"/>
		<updated>2012-10-26T21:01:58Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Facade is more like a simple gateway to a complicated set of functionality. You make a black-box for your clients to worry less i.e. make interfaces simpler&lt;br /&gt;
*Where as decorator is used to add more gunpowder to your objects (note the term objects -- you typically decorate objects dynamically at runtime). You do not hide/impair the existing interfaces of the object but simply extend it at runtime.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Composite pattern and Decorator pattern===&lt;br /&gt;
*The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity.&lt;br /&gt;
*The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity&lt;br /&gt;
*Composite pattern: gives an unified interface to a leaf and composite.&lt;br /&gt;
*Decorator: composite gives additional feature to leaf, while giving unified interface.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;br /&gt;
*[http://stackoverflow.com/questions/2233952/difference-between-the-composite-pattern-and-decorator-pattern Composite vs Decorator]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68250</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68250"/>
		<updated>2012-10-26T21:01:17Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Comparisons */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Facade is more like a simple gateway to a complicated set of functionality. You make a black-box for your clients to worry less i.e. make interfaces simpler&lt;br /&gt;
*Where as decorator is used to add more gunpowder to your objects (note the term objects -- you typically decorate objects dynamically at runtime). You do not hide/impair the existing interfaces of the object but simply extend it at runtime.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Composite pattern and Decorator pattern===&lt;br /&gt;
*The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity.&lt;br /&gt;
*The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity&lt;br /&gt;
*Composite pattern: gives an unified interface to a leaf and composite.&lt;br /&gt;
*Decorator: composite gives additional feature to leaf, while giving unified interface.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68242</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68242"/>
		<updated>2012-10-26T20:36:29Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Comparison of Decorator pattern and Facade pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Facade is more like a simple gateway to a complicated set of functionality. You make a black-box for your clients to worry less i.e. make interfaces simpler&lt;br /&gt;
*Where as decorator is used to add more gunpowder to your objects (note the term objects -- you typically decorate objects dynamically at runtime). You do not hide/impair the existing interfaces of the object but simply extend it at runtime.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68241</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68241"/>
		<updated>2012-10-26T20:35:17Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;br /&gt;
*[http://sarosh.wordpress.com/2009/09/22/difference-between-facade-and-decorator-pattern/ Decorator vs Facade]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68239</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68239"/>
		<updated>2012-10-26T20:34:53Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Comparisons */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===Comparison of Decorator pattern and Facade pattern===&lt;br /&gt;
*Facade gives the impression that your create a facade object over different desperate objects, or you actually decorate them with another layer, or they are two different name for the same pattern&lt;br /&gt;
*Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically, it also provides a flexible alternative to sub classing for extending functionality.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68238</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68238"/>
		<updated>2012-10-26T20:29:48Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow- Difference between adapter and bridge pattern]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68237</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68237"/>
		<updated>2012-10-26T20:29:30Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern Stack Overflow]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68236</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68236"/>
		<updated>2012-10-26T20:29:00Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
*[http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68235</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68235"/>
		<updated>2012-10-26T20:28:41Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;br /&gt;
http://stackoverflow.com/questions/1425171/difference-between-bridge-pattern-and-adapter-pattern&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68234</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68234"/>
		<updated>2012-10-26T20:28:28Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Comparison of Bridge pattern and Adapter pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*A Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68233</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w17 pt</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w17_pt&amp;diff=68233"/>
		<updated>2012-10-26T20:27:55Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Comparisons */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Design Pattern==&lt;br /&gt;
	A [http://en.wikipedia.org/wiki/Software_design_pattern software design pattern] is a problem-solution pair that gives a general re-usable solution to a commonly occurring problem and can be applied in a similar fashion in new contexts. A design pattern is a [http://en.wikipedia.org/wiki/Template template] that gives a solution to many similar situations. It cannot be directly transformed into code.  &lt;br /&gt;
The solution is usually a simple mechanism because it is a collaboration between two or more [http://en.wikipedia.org/wiki/Class_%28computer_programming%29 classes], [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCYQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObject_(computer_science)&amp;amp;ei=e8x9UP76EYfO9QSaqIHgAw&amp;amp;usg=AFQjCNEi_fFQxGdN5EgaYjs39AP1_WV9Vg objects], services, processes, [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=3&amp;amp;cad=rja&amp;amp;ved=0CDgQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FThread_(computing)&amp;amp;ei=jMx9UJDfFofA9gSCvYDIBA&amp;amp;usg=AFQjCNHVNxWptDxJ9hDcMD_N5JtVFZX9Ow threads], components, or nodes that work together to solve the underlying architecture or development challenge&lt;br /&gt;
	Design patterns documents simple mechanism that work. They provide a common vocabulary and taxonomy for developers and architects. They allow solutions to be described concisely as combinations of patterns. They enable reuse of architecture, design, and implementation decisions. All these features make design patterns very useful to software developers and architects.&lt;br /&gt;
	Design patterns are typically represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. For instance consider the Adapter pattern. [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=2&amp;amp;cad=rja&amp;amp;sqi=2&amp;amp;ved=0CCoQFjAB&amp;amp;url=http%3A%2F%2Fwww.oodesign.com%2Fadapter-pattern.html&amp;amp;ei=u8x9UMmUI4aK8QSE7YHoDg&amp;amp;usg=AFQjCNHBiT1X1w8RNvDaj_11MvharrKziA Adapter pattern] provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are not compatible. To implement the Adapter pattern, you create a custom class that honors the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.&lt;br /&gt;
	There are many design patterns like [http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCcQFjAA&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FStrategy_pattern&amp;amp;ei=zcx9UMKnFIXA9gTVmIHwCQ&amp;amp;usg=AFQjCNGl3o_1x2n2_FUSSLX9qu5qjlOGmA Algorithm strategy patterns], [http://www.computationaldesign.ca/projects Computational design patterns], [http://pic.dhe.ibm.com/infocenter/brjrules/v7r1/index.jsp?topic=%2Fcom.ibm.websphere.ilog.jrules.doc%2FContent%2FBusiness_Rules%2FDocumentation%2F_pubskel%2FJRules%2Fps_JRules_Global933.html Execution patterns], [http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Implementation strategy patterns], [http://gsraj.tripod.com/design/structural.html Structural design patterns].&lt;br /&gt;
&lt;br /&gt;
==Proxy pattern==&lt;br /&gt;
	The [http://en.wikipedia.org/wiki/Proxy_pattern Proxy pattern], also known as a surrogate pattern, is a Structural design pattern. A proxy provides a surrogate or placeholder for another object to control access to it. There will be situations in which a client does not or cannot reference an object directly but still wants to interact with the object. A proxy object can act as an intermediary between the client and the target object. A [http://msdn.microsoft.com/en-us/library/windows/desktop/dd373867%28v=vs.85%29.aspx proxy object] has the same interface as the target object. The proxy holds a reference to the target object and can forward requests to the target as required. In effect, the proxy object has the authority to act on behalf of the client to interact with the target object.&lt;br /&gt;
&lt;br /&gt;
==UML Class Diagram==&lt;br /&gt;
&lt;br /&gt;
[[File:pt.jpg]]	&lt;br /&gt;
&lt;br /&gt;
By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.&lt;br /&gt;
&lt;br /&gt;
==Applications of Proxy Pattern==&lt;br /&gt;
*A proxy can interface a network connection, a large object in memory, a file or any other resource that is expensive or impossible to duplicate.  &lt;br /&gt;
*Proxies are useful wherever there is a need for a more sophisticated reference to a object than a simple pointer or simple reference can provide.&lt;br /&gt;
*In situations where multiple copies of a complex object must exist, the proxy pattern can be used to reduce the application’s memory requirements. A single instance of the complex object and multiple proxy objects are created all of which are references to the original complex object. Any operation on the proxy is forwarded to the original object.&lt;br /&gt;
&lt;br /&gt;
==Types of proxies==&lt;br /&gt;
===Remote Proxy===&lt;br /&gt;
A [http://c2.com/cgi/wiki?RemoteProxy remote proxy] provides a reference to an object located in a different address space on the same or different machine. They are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.&lt;br /&gt;
&lt;br /&gt;
===Virtual Proxy===&lt;br /&gt;
A [http://www.javabeat.net/2007/09/working-with-virtual-proxy-pattern/ virtual proxy] allows the creation of a memory intensive object on demand. The object will not be created until it is really needed.&lt;br /&gt;
&lt;br /&gt;
===Copy-on-Write Proxy===&lt;br /&gt;
A [http://users.soe.ucsc.edu/~pohl/Winter01/Design2/sld047.htm copy-on-write] defers cloning a target object until required by client actions. It is really a form of virtual proxy.&lt;br /&gt;
&lt;br /&gt;
===Protection Proxy===&lt;br /&gt;
A [http://www.cymphonix.com/AnonymousProxy.html protection proxy] provides different clients with different levels of access to a target object.&lt;br /&gt;
&lt;br /&gt;
===Cache Proxy===&lt;br /&gt;
A [http://www.blackwasp.co.uk/Proxy.aspx cache proxy] provides temporary storage of the results of expensive target operations so that multiple clients can share the results.&lt;br /&gt;
&lt;br /&gt;
===Firewall Proxy===&lt;br /&gt;
A [http://www.cs.sjsu.edu/~pearce/oom/patterns/behavioral/proxy.htm firewall proxy] protects targets from bad clients (or vice versa).&lt;br /&gt;
&lt;br /&gt;
===Synchronization Proxy===&lt;br /&gt;
A [http://rezagh.wikidot.com/sync-proxy-pattern synchronization proxy] provides multiple accesses to a target object.&lt;br /&gt;
&lt;br /&gt;
===Smart reference Proxy===&lt;br /&gt;
A [http://www.theserverside.com/discussions/thread.tss?thread_id=10880 smart reference proxy] provides additional actions whenever a target object is referenced such as counting the number of references to the object.&lt;br /&gt;
&lt;br /&gt;
==Examples of Proxy pattern==&lt;br /&gt;
===C++===&lt;br /&gt;
====Example 1====&lt;br /&gt;
 class RealImage&lt;br /&gt;
 {&lt;br /&gt;
     int m_id;&lt;br /&gt;
     public:&lt;br /&gt;
     RealImage(int i)&lt;br /&gt;
     {&lt;br /&gt;
        m_id = i;&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   $$ ctor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
     }&lt;br /&gt;
    ~RealImage()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   dtor: &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; &amp;quot;   drawing image &amp;quot; &amp;lt;&amp;lt; m_id &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 // 1. Design an &amp;quot;extra level of indirection&amp;quot; wrapper class&lt;br /&gt;
 class Image&lt;br /&gt;
 {&lt;br /&gt;
    // 2. The wrapper class holds a pointer to the real class&lt;br /&gt;
    RealImage *m_the_real_thing;&lt;br /&gt;
    int m_id;&lt;br /&gt;
    static int s_next;&lt;br /&gt;
  public:&lt;br /&gt;
    Image()&lt;br /&gt;
    {&lt;br /&gt;
        m_id = s_next++;&lt;br /&gt;
        // 3. Initialized to null&lt;br /&gt;
        m_the_real_thing = 0;&lt;br /&gt;
    }&lt;br /&gt;
    ~Image()&lt;br /&gt;
    {&lt;br /&gt;
        delete m_the_real_thing;&lt;br /&gt;
    }&lt;br /&gt;
    void draw()&lt;br /&gt;
    {&lt;br /&gt;
        // 4. When a request comes in, the real object is&lt;br /&gt;
        //    created &amp;quot;on first use&amp;quot;&lt;br /&gt;
        if (!m_the_real_thing)&lt;br /&gt;
          m_the_real_thing = new RealImage(m_id);&lt;br /&gt;
        // 5. The request is always delegated&lt;br /&gt;
        m_the_real_thing-&amp;gt;draw();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int Image::s_next = 1;&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  Image images[5];&lt;br /&gt;
  for (int i; true;)&lt;br /&gt;
  {&lt;br /&gt;
    cout &amp;lt;&amp;lt; &amp;quot;Exit[0], Image[1-5]: &amp;quot;;&lt;br /&gt;
    cin &amp;gt;&amp;gt; i;&lt;br /&gt;
    if (i == 0)&lt;br /&gt;
      break;&lt;br /&gt;
    images[i - 1].draw();&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*The Wrapper class has an extra level on indirection&lt;br /&gt;
*The Wrapper class contains a pointer to the original class and it is initialized to NULL&lt;br /&gt;
*Lazy initialization is implemented.&lt;br /&gt;
*Request is always delegated.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 $$ ctor: 2 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 4 &lt;br /&gt;
 $$ ctor: 4 drawing image 4 &lt;br /&gt;
 Exit[0], Image[1-5]: 2 &lt;br /&gt;
 drawing image 2 &lt;br /&gt;
 Exit[0], Image[1-5]: 0 &lt;br /&gt;
 dtor: 4 &lt;br /&gt;
 dtor: 2&lt;br /&gt;
&lt;br /&gt;
====Exmaple 2====&lt;br /&gt;
 class Subject&lt;br /&gt;
 {&lt;br /&gt;
  public:&lt;br /&gt;
    virtual void execute() = 0;&lt;br /&gt;
 };&lt;br /&gt;
 class RealSubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string str;&lt;br /&gt;
  public:&lt;br /&gt;
    RealSubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        str = s;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; '\n';&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 class ProxySubject: public Subject&lt;br /&gt;
 {&lt;br /&gt;
    string first, second, third;&lt;br /&gt;
    RealSubject *ptr;&lt;br /&gt;
  public:&lt;br /&gt;
    ProxySubject(string s)&lt;br /&gt;
    {&lt;br /&gt;
        int num = s.find_first_of(' ');&lt;br /&gt;
        first = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        second = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        num = s.find_first_of(' ');&lt;br /&gt;
        third = s.substr(0, num);&lt;br /&gt;
        s = s.substr(num + 1);&lt;br /&gt;
        ptr = new RealSubject(s);&lt;br /&gt;
    }&lt;br /&gt;
    ~ProxySubject()&lt;br /&gt;
    {&lt;br /&gt;
        delete ptr;&lt;br /&gt;
    }&lt;br /&gt;
    RealSubject *operator-&amp;gt;()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; second &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        return ptr;&lt;br /&gt;
    }&lt;br /&gt;
     /*virtual*/void execute()&lt;br /&gt;
    {&lt;br /&gt;
        cout &amp;lt;&amp;lt; first &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; third &amp;lt;&amp;lt; ' ';&lt;br /&gt;
        ptr-&amp;gt;execute();&lt;br /&gt;
    }&lt;br /&gt;
 };&lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
  ProxySubject obj(string(&amp;quot;the quick brown fox jumped over the dog&amp;quot;));&lt;br /&gt;
  obj-&amp;gt;execute();&lt;br /&gt;
  obj.execute();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*Here ”-&amp;gt;” and “.” operators give different results.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 the quick fox jumped over the dog &lt;br /&gt;
 the brown fox jumped over the dog&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
 import java.io.*;  import java.net.*;&lt;br /&gt;
 // 5. To be compatible, an interface is created between the proxy and target&lt;br /&gt;
 interface SocketInterface {&lt;br /&gt;
  String readLine();&lt;br /&gt;
  void  writeLine( String str );&lt;br /&gt;
  void  dispose();&lt;br /&gt;
 }&lt;br /&gt;
 public class ProxyDemo {&lt;br /&gt;
  public static void main( String[] args ) {&lt;br /&gt;
    // 3. The client deals with the proxy&lt;br /&gt;
    SocketInterface socket = new SocketProxy( &amp;quot;127.0.0.1&amp;quot;, 8189,&lt;br /&gt;
      args[0].equals(&amp;quot;first&amp;quot;) ? true : false );&lt;br /&gt;
    String  str = null;&lt;br /&gt;
    boolean skip = true;&lt;br /&gt;
    while (true) {&lt;br /&gt;
      if (args[0].equals(&amp;quot;second&amp;quot;)  &amp;amp;&amp;amp;  skip) {&lt;br /&gt;
        skip = ! skip;&lt;br /&gt;
      }&lt;br /&gt;
      else {&lt;br /&gt;
        str = socket.readLine();&lt;br /&gt;
        System.out.println( &amp;quot;Receive - &amp;quot; + str );  // java ProxyDemo first&lt;br /&gt;
        if (str.equals(&amp;quot;quit&amp;quot;)) break;             // Receive - 123 456&lt;br /&gt;
      }                                            // Send ---- 234 567&lt;br /&gt;
      System.out.print( &amp;quot;Send ---- &amp;quot; );            // Receive - 345 678&lt;br /&gt;
      str = Read.aString();                        //&lt;br /&gt;
      socket.writeLine( str );                     // java ProxyDemo second&lt;br /&gt;
      if (str.equals(&amp;quot;quit&amp;quot;)) break;               // Send ---- 123 456&lt;br /&gt;
    }                                              // Receive - 234 567&lt;br /&gt;
    socket.dispose();                              // Send ---- 345 678&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 class SocketProxy implements SocketInterface {&lt;br /&gt;
  // 1. A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
  private Socket      socket;&lt;br /&gt;
  private BufferedReader in;&lt;br /&gt;
  private PrintWriter   out;&lt;br /&gt;
  public SocketProxy( String host, int port, boolean wait ) {&lt;br /&gt;
    try {&lt;br /&gt;
      if (wait) {&lt;br /&gt;
        // 2. A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
        ServerSocket server = new ServerSocket( port );&lt;br /&gt;
        socket = server.accept();&lt;br /&gt;
      } else&lt;br /&gt;
        socket = new Socket( host, port );&lt;br /&gt;
        in  = new BufferedReader( new InputStreamReader(&lt;br /&gt;
                                        socket.getInputStream()));&lt;br /&gt;
        out = new PrintWriter( socket.getOutputStream(), true );&lt;br /&gt;
      } catch( IOException e ) {&lt;br /&gt;
        e.printStackTrace();&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
  public String readLine() {&lt;br /&gt;
    String str = null;&lt;br /&gt;
    try {&lt;br /&gt;
      str = in.readLine();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return str;&lt;br /&gt;
  }&lt;br /&gt;
  public void writeLine( String str ) {&lt;br /&gt;
    // 4. The proxy delegates the target&lt;br /&gt;
    out.println( str );&lt;br /&gt;
  }&lt;br /&gt;
  public void dispose() {&lt;br /&gt;
    try {&lt;br /&gt;
      socket.close();&lt;br /&gt;
    } catch( IOException e ) {&lt;br /&gt;
      e.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A proxy is created for the expensive or remote or sensitive object(target)&lt;br /&gt;
*A level of abstraction is created to encapsulate the complexity is the target&lt;br /&gt;
*The client deals with the proxy&lt;br /&gt;
*The proxy delegates the target&lt;br /&gt;
*To be compatible, an interface is created between the proxy and target.&lt;br /&gt;
&lt;br /&gt;
===C#===&lt;br /&gt;
 using System;&lt;br /&gt;
  // MainApp test application &lt;br /&gt;
  class MainApp&lt;br /&gt;
  {&lt;br /&gt;
    static void Main()&lt;br /&gt;
    {&lt;br /&gt;
      // Create proxy and request a service &lt;br /&gt;
      Proxy proxy = new Proxy();&lt;br /&gt;
      proxy.Request();&lt;br /&gt;
      // Wait for user &lt;br /&gt;
      Console.Read();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Subject&amp;quot; &lt;br /&gt;
  abstract class Subject &lt;br /&gt;
  {&lt;br /&gt;
    public abstract void Request();    &lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;RealSubject&amp;quot; &lt;br /&gt;
  class RealSubject : Subject&lt;br /&gt;
  {&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      Console.WriteLine(&amp;quot;Called RealSubject.Request()&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  // &amp;quot;Proxy&amp;quot; &lt;br /&gt;
  class Proxy : Subject&lt;br /&gt;
  {&lt;br /&gt;
    RealSubject realSubject;&lt;br /&gt;
    public override void Request()&lt;br /&gt;
    {&lt;br /&gt;
      // Use 'lazy initialization' &lt;br /&gt;
      if (realSubject == null)&lt;br /&gt;
      {&lt;br /&gt;
        realSubject = new RealSubject();&lt;br /&gt;
      }&lt;br /&gt;
      realSubject.Request();&lt;br /&gt;
    }  &lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
*A surrogate is provided for another object to control access to it.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 Called RealSubject.Request()&lt;br /&gt;
&lt;br /&gt;
===PHP===&lt;br /&gt;
 &amp;lt;?php&lt;br /&gt;
 class ProxyBookList {&lt;br /&gt;
    private $bookList = NULL; &lt;br /&gt;
    //bookList is not instantiated at construct time&lt;br /&gt;
    function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    function getBookCount() {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    function addBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList(); &lt;br /&gt;
        }&lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;addBook($book);&lt;br /&gt;
    }  &lt;br /&gt;
    function getBook($bookNum) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;getBook($bookNum);&lt;br /&gt;
    }&lt;br /&gt;
    function removeBook($book) {&lt;br /&gt;
        if (NULL == $this-&amp;gt;bookList) {&lt;br /&gt;
            $this-&amp;gt;makeBookList();&lt;br /&gt;
        } &lt;br /&gt;
        return $this-&amp;gt;bookList-&amp;gt;removeBook($book);&lt;br /&gt;
    }&lt;br /&gt;
    //Create &lt;br /&gt;
    function makeBookList() {&lt;br /&gt;
        $this-&amp;gt;bookList = new bookList();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class BookList {&lt;br /&gt;
    private $books = array();&lt;br /&gt;
    private $bookCount = 0;&lt;br /&gt;
    public function __construct() {&lt;br /&gt;
    }&lt;br /&gt;
    public function getBookCount() {&lt;br /&gt;
        return $this-&amp;gt;bookCount;&lt;br /&gt;
    }&lt;br /&gt;
    private function setBookCount($newCount) {&lt;br /&gt;
        $this-&amp;gt;bookCount = $newCount;&lt;br /&gt;
    }&lt;br /&gt;
    public function getBook($bookNumberToGet) {&lt;br /&gt;
        if ( (is_numeric($bookNumberToGet)) &amp;amp;&amp;amp; ($bookNumberToGet &amp;lt;= $this-&amp;gt;getBookCount())) {&lt;br /&gt;
            return $this-&amp;gt;books[$bookNumberToGet];&lt;br /&gt;
        } else {&lt;br /&gt;
           return NULL;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public function addBook(Book $book_in) {&lt;br /&gt;
        $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() + 1);&lt;br /&gt;
        $this-&amp;gt;books[$this-&amp;gt;getBookCount()] = $book_in;&lt;br /&gt;
        return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
    public function removeBook(Book $book_in) {&lt;br /&gt;
        $counter = 0;&lt;br /&gt;
        while (++$counter &amp;lt;= $this-&amp;gt;getBookCount()) {&lt;br /&gt;
          if ($book_in-&amp;gt;getAuthorAndTitle() == $this-&amp;gt;books[$counter]-&amp;gt;getAuthorAndTitle()) {&lt;br /&gt;
            for ($x = $counter; $x &amp;lt; $this-&amp;gt;getBookCount(); $x++) {&lt;br /&gt;
              $this-&amp;gt;books[$x] = $this-&amp;gt;books[$x + 1];&lt;br /&gt;
          }&lt;br /&gt;
          $this-&amp;gt;setBookCount($this-&amp;gt;getBookCount() - 1);&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
      return $this-&amp;gt;getBookCount();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class Book {&lt;br /&gt;
    private $author;&lt;br /&gt;
    private $title;&lt;br /&gt;
    function __construct($title_in, $author_in) {&lt;br /&gt;
      $this-&amp;gt;author = $author_in;&lt;br /&gt;
      $this-&amp;gt;title  = $title_in;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthor() {&lt;br /&gt;
        return $this-&amp;gt;author;&lt;br /&gt;
    }&lt;br /&gt;
    function getTitle() {&lt;br /&gt;
        return $this-&amp;gt;title;&lt;br /&gt;
    }&lt;br /&gt;
    function getAuthorAndTitle() {&lt;br /&gt;
      return $this-&amp;gt;getTitle().' by '.$this-&amp;gt;getAuthor();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  writeln( 'BEGIN TESTING PROXY PATTERN';&lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList = new ProxyBookList();&lt;br /&gt;
  $inBook = new Book('PHP for Cats','Larry Truett');&lt;br /&gt;
  $proxyBookList-&amp;gt;addBook($inBook);&lt;br /&gt;
  writeln('test 1 - show the book count after a book is added');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('test 2 - show the book');&lt;br /&gt;
  $outBook = $proxyBookList-&amp;gt;getBook(1);&lt;br /&gt;
  writeln($outBook-&amp;gt;getAuthorAndTitle()); &lt;br /&gt;
  writeln('');&lt;br /&gt;
  $proxyBookList-&amp;gt;removeBook($outBook);&lt;br /&gt;
  writeln('test 3 - show the book count after a book is removed');&lt;br /&gt;
  writeln($proxyBookList-&amp;gt;getBookCount());&lt;br /&gt;
  writeln('');&lt;br /&gt;
  writeln('END TESTING PROXY PATTERN');&lt;br /&gt;
  function writeln($line_in) {&lt;br /&gt;
    echo $line_in.&amp;quot;&amp;lt;br/&amp;gt;&amp;quot;;&lt;br /&gt;
  }&lt;br /&gt;
 ?&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Explanation of Proxy Pattern'''&lt;br /&gt;
* ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.&lt;br /&gt;
&lt;br /&gt;
'''Output'''&lt;br /&gt;
 BEGIN TESTING PROXY PATTERN &lt;br /&gt;
 test 1 - show the book count after a book is added &lt;br /&gt;
 1 &lt;br /&gt;
 test 2 - show the book &lt;br /&gt;
 PHP for Cats by Larry Truett &lt;br /&gt;
 test 3 - show the book count after a book is removed &lt;br /&gt;
 0 &lt;br /&gt;
 END TESTING PROXY PATTERN&lt;br /&gt;
&lt;br /&gt;
==Similar patterns==&lt;br /&gt;
===Adapter Pattern===&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html adapter pattern] translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface&lt;br /&gt;
&lt;br /&gt;
===Bridge Pattern===&lt;br /&gt;
A [http://www.oodesign.com/bridge-pattern.html Bridge Pattern] decouples an abstraction from its implementation so that the two can vary independently&amp;quot;. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.&lt;br /&gt;
&lt;br /&gt;
===Composite Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternComposite.aspx composite pattern] is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &amp;quot;compose&amp;quot; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
The [http://www.oodesign.com/decorator-pattern.html decorator pattern] can be used to extend (decorate) the functionality of a certain object dynamically, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.&lt;br /&gt;
&lt;br /&gt;
===Facade Pattern===&lt;br /&gt;
A [http://www.dofactory.com/Patterns/PatternFacade.aspx facade] is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can make a software library easier to use, understand and test, since the facade has convenient methods for common tasks. It can make the library more readable, for the same reason. It can reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system. It wraps a poorly designed collection of API’s with a single well-designed API .&lt;br /&gt;
&lt;br /&gt;
===Flyweight Pattern===&lt;br /&gt;
A [http://www.oodesign.com/flyweight-pattern.html flyweight] is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.&lt;br /&gt;
&lt;br /&gt;
===Front Controller Pattern===&lt;br /&gt;
[http://www.corej2eepatterns.com/Patterns2ndEd/FrontController.htm Front controllers] are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.&lt;br /&gt;
&lt;br /&gt;
===Module Pattern===&lt;br /&gt;
A [http://briancray.com/posts/javascript-module-pattern module pattern] is a design pattern used to implement the concept of software modules,     defined by modular programming, in a programming language that does not support it, or only supports it, partially.&lt;br /&gt;
&lt;br /&gt;
==Comparisons==&lt;br /&gt;
===Comparison of Proxy pattern and Facade Pattern===&lt;br /&gt;
*The proxy pattern adds behavior whereas the façade pattern simplifies behavior.&lt;br /&gt;
*Proxies are optional, facades are not.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Adapter Pattern and Facade Pattern===&lt;br /&gt;
*In adapter pattern, the interface that is being adapted might already exist. &lt;br /&gt;
*The adapter pattern preserves polymorphism. A façade provides an idealized flexible interface which can be modified anytime as requirements come in.&lt;br /&gt;
*Adapters are usually small and hence do not have performance issues whereas facades are huge.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Proxy pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*In adapter pattern client can use the service entity only by using the adapter whereas in proxy pattern a client can use the proxy or the adapter in the same way.&lt;br /&gt;
*The Proxy can be cast to the interface of the Service. The Adapter can be cast to the interface the Client expects.&lt;br /&gt;
&lt;br /&gt;
===Comparison of Bridge pattern and Adapter pattern===&lt;br /&gt;
*An adapter pattern changes the interface of the service whereas proxy pattern changes the behavior.&lt;br /&gt;
*An adapter pattern preserves the behavior of the service whereas the proxy pattern preserves the interface.&lt;br /&gt;
*Bridge pattern serves to decouple an abstraction class from its implementation, where as an adaptor pattern converts between classes with less inheritance &lt;br /&gt;
*One main difference according to GOF is that &amp;quot;Adapter makes things work after they're designed; Bridge makes them work before they are&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*http://en.wikipedia.org/wiki/Software_design_pattern&lt;br /&gt;
*http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy&lt;br /&gt;
*http://www.dofactory.com/Patterns/&lt;br /&gt;
*http://en.wikipedia.org/wiki/Proxy_pattern&lt;br /&gt;
*http://www.oodesign.com/&lt;br /&gt;
*http://www.netobjectivestest.com/PatternRepository/index.php?title=AdapterVersusProxyVersusFacadePatternComparison&lt;br /&gt;
*[http://www.csc.ncsu.edu/faculty/efg/517/f12/schedule Class notes]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&amp;amp;tp=&amp;amp;arnumber=4383091&amp;amp;contentType=Conference+Publications&amp;amp;sortType%3Dasc_p_Sequence%26filter%3DAND%28p_IS_Number%3A4383083%29 IEEE paper 1]&lt;br /&gt;
*[http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;amp;arnumber=5982228&amp;amp;url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D5982228 IEEE Paper 2]&lt;br /&gt;
*[http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCkQFjAA&amp;amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.75.3386%26rep%3Drep1%26type%3Dpdf&amp;amp;ei=Vdp9UKinJpD09gTr8oCwDA&amp;amp;usg=AFQjCNERJnpeBDZjXH6PrZnR_8zRQPkIZQ IEEE Paper 3]&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65370</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65370"/>
		<updated>2012-09-20T19:57:46Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;ref&amp;gt;{{ url=http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy |title=Performance comparison |accessdate=2012-06-0 }}&amp;lt;/ref&amp;gt;.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time - Difficulty over Java. &amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension - Difficulty over Ruby.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] Ruby Performance&lt;br /&gt;
| name rubyPerf&lt;br /&gt;
| website= JRubyhttp://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65369</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65369"/>
		<updated>2012-09-20T19:57:19Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;ref&amp;gt;{{ url=http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy |title=Performance comparison |accessdate=2012-06-0 }}&amp;lt;/ref&amp;gt;.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time - Difficulty over Java. &amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension - Difficulty over Ruby.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] {{Ruby Performance&lt;br /&gt;
| name rubyPerf&lt;br /&gt;
| website= JRubyhttp://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy}}&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65368</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65368"/>
		<updated>2012-09-20T19:51:06Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Advantages of JRuby over Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;ref&amp;gt;{{ url=http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy |title=Performance comparison |accessdate=2012-06-0 }}&amp;lt;/ref&amp;gt;.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time - Difficulty over Java. &amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension - Difficulty over Ruby.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65367</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65367"/>
		<updated>2012-09-20T19:50:46Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Advantages of JRuby over Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;ref&amp;gt;{{cite web|url=http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy |title=Performance comparison |accessdate=2012-06-0 }}&amp;lt;/ref&amp;gt;.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time - Difficulty over Java. &amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension - Difficulty over Ruby.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65366</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65366"/>
		<updated>2012-09-20T19:50:09Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Advantages of JRuby over Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;ref&amp;gt;{{cite web|url=http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy |title=Performance comparison |accessdate=2012-06-02 |date=2009-07-28publisher=[[PCWorld (magazine)|PCWorld]]}}&amp;lt;/ref&amp;gt;.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time - Difficulty over Java. &amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension - Difficulty over Ruby.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65365</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65365"/>
		<updated>2012-09-20T19:47:01Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Advantages of JRuby over Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;ref name=&amp;quot;engineyardmove&amp;quot;&amp;gt;{{cite web|url=http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy |title=Performance comparison |accessdate=2012-06-02 |date=2009-07-28publisher=[[PCWorld (magazine)|PCWorld]]}}&amp;lt;/ref&amp;gt;.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time - Difficulty over Java. &amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension - Difficulty over Ruby.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65364</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65364"/>
		<updated>2012-09-20T19:45:36Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Advantages of JRuby over Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;ref name=&amp;quot;engineyardmove&amp;quot;&amp;gt;{{cite web|url=http://www.pcworld.com/article/169145/suns_jruby_team_jumps_ship_to_engine_yard.html |title=Sun's JRuby Team Jumps Ship to Engine Yard |accessdate=2012-06-02 |date=2009-07-28publisher=[[PCWorld (magazine)|PCWorld]]}}&amp;lt;/ref&amp;gt;.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time - Difficulty over Java. &amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension - Difficulty over Ruby.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65363</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65363"/>
		<updated>2012-09-20T19:43:28Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties with JRuby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time - Difficulty over Java. &amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension - Difficulty over Ruby.&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65362</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=65362"/>
		<updated>2012-09-20T19:42:58Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some of the difficulties which are observed when these two types of object orientation are mixed. We will then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic object oriented code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static object oriented code makes use of generics.&amp;lt;br&amp;gt; For example, in case we are using Java, the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you have to undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved using the following two flavors.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* JRuby runs faster than Ruby, except at startup. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following good features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby Explained ==&lt;br /&gt;
In addition to the advantages mentioned in the above section, some other features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
Let us see the two implementations of JRuby.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
The steps are:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
For example if we have a ruby method that returns a string object then we can convert it into a java.lang.String object on the Java side. The table shown below provides a quick overview of the mapping of types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt; - Difficulty over Java.&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that we can expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt; Difficulty over Ruby.&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI. However, big frameworks like Rails are tested with JRuby.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. JRuby combines a lot of advantages of Java and Ruby by enabling us to reopen Java Classes, mixing Java interfaces in Ruby, letting JRuby classes implement more than one Java interface by mixing the interfaces in the classes, catching the native Java exceptions and throwing them via Ruby code etc. There are three ways of calling Ruby from Java namely Embedding JRuby, using JSR 223 and by using the Bean Scripting Framework and this provides better flexibility to the programmer. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&amp;lt;br&amp;gt;&lt;br /&gt;
[12] http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby: Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64995</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64995"/>
		<updated>2012-09-15T01:06:09Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties with JRuby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively.  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On an average JRuby, runs two and a half times faster than Ruby, except at startup. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
Some of the important features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types. The table below shows this conversion.&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than [http://en.wikipedia.org/wiki/Ruby_MRI MRI].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64990</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64990"/>
		<updated>2012-09-15T01:03:09Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* JSR 223, Scripting for the Java Platform */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively.  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On an average JRuby, runs two and a half times faster than Ruby, except at startup. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
Some of the important features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64988</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64988"/>
		<updated>2012-09-15T01:02:18Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* JSR 223, Scripting for the Java Platform */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively.  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to the native libraries you can access Java libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On an average JRuby, runs two and a half times faster than Ruby, except at startup. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language. &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has the following features which are missing from Java. &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
Some of the important features of JRuby are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes. This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like. Note that these additions will be visible only on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is sometimes necessary to synchronize on an object for thread safety. To support this functionality, in JRuby, a synchronize method is provided on every wrapped Java object.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby code. This includes adding some Java functionality in the Ruby code. The final code will be run on the JVM. Ruby code can load and interact with Java libraries. As a simple example we can use an ArrayList from Java and integrate it with the Ruby code as seen below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as name conflicts in both Ruby and Java can result in losing the Ruby functionality. For example, if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using: &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create a new file using the File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. The following code shows an example of embedding Ruby in Java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the lib folder of the JRuby installation directory. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. The JSR 223 Scripting APIs can be used with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
*Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&amp;lt;br&amp;gt;*Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&amp;lt;br&amp;gt;*Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above program prints &amp;quot;Hello&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64965</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64965"/>
		<updated>2012-09-15T00:47:29Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Advantages of JRuby over Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively.  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
JRuby features are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.Note that these additions will only be visible on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a synchronize method is provided on every wrapped Java object to support this functionality.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64964</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64964"/>
		<updated>2012-09-15T00:46:10Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
JRuby features are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.Note that these additions will only be visible on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a synchronize method is provided on every wrapped Java object to support this functionality.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64960</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64960"/>
		<updated>2012-09-15T00:42:22Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspects in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
JRuby features are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.Note that these additions will only be visible on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a synchronize method is provided on every wrapped Java object to support this functionality.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conversion of Types ==&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64935</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64935"/>
		<updated>2012-09-15T00:26:48Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* JRuby explained */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
JRuby features are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.Note that these additions will only be visible on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a synchronize method is provided on every wrapped Java object to support this functionality.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64933</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64933"/>
		<updated>2012-09-15T00:26:31Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* JRuby explained */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
JRuby features are:&amp;lt;br&amp;gt;*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.Note that these additions will only be visible on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a synchronize method is provided on every wrapped Java object to support this functionality.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64928</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64928"/>
		<updated>2012-09-15T00:25:24Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
JRuby features are:&lt;br /&gt;
*Reopening Java Classes&amp;lt;br&amp;gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.&lt;br /&gt;
This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.&lt;br /&gt;
Note that these additions will only be visible on the JRuby side.&lt;br /&gt;
*Mixing Java Interfaces &amp;lt;br&amp;gt; JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
*Exception handling &amp;lt;br&amp;gt; Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
*Synchronization &amp;lt;br&amp;gt; When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a synchronize method is provided on every wrapped Java object to support this functionality.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64917</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64917"/>
		<updated>2012-09-15T00:22:07Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Advantages of JRuby over Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
* JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. If you do not want this behaviour for a specific class, you can undefine it for that class.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL).&lt;br /&gt;
&lt;br /&gt;
In addition to the above, JRuby has other features like &lt;br /&gt;
**Reopening Java Classes&lt;br /&gt;
In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.&lt;br /&gt;
This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.&lt;br /&gt;
Note that these additions will only be visible on the JRuby side.&lt;br /&gt;
** Mixing Java Interfaces &lt;br /&gt;
JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.&lt;br /&gt;
** Exception handling&lt;br /&gt;
Native Java exceptions can be caught and thrown in Ruby code.&lt;br /&gt;
** Synchronization &lt;br /&gt;
When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a synchronize method is provided on every wrapped Java object to support this functionality.&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64882</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64882"/>
		<updated>2012-09-15T00:04:09Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /*  Driving Java from Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
When primitive Java types are passed to JRuby they are converted to the following Ruby types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64881</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64881"/>
		<updated>2012-09-15T00:03:44Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /*  Driving Java from Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Java Type &amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Ruby Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | public String || String&lt;br /&gt;
   |-&lt;br /&gt;
   | public byte || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public short || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public char || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public int || Fixnum&lt;br /&gt;
   |-&lt;br /&gt;
   | public float || Float&lt;br /&gt;
   |-&lt;br /&gt;
   | public double|| Float&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64870</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64870"/>
		<updated>2012-09-14T23:59:23Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* JRuby explained in details */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64864</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64864"/>
		<updated>2012-09-14T23:56:40Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /*  Driving Java from Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;quot;foo&amp;quot; || java.lang.String&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.lang.Long&lt;br /&gt;
   |-&lt;br /&gt;
   | 1.0 || java.lang.Double&lt;br /&gt;
   |-&lt;br /&gt;
   | true, false|| java.lang.Boolean&lt;br /&gt;
   |-&lt;br /&gt;
   | 1|| java.math.BigInteger&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64861</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64861"/>
		<updated>2012-09-14T23:54:53Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /*  Driving Java from Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
 {| style=&amp;quot;background:#FFFFFB; margin-left: 4em;&amp;quot; border=&amp;quot;1&amp;quot; cellpadding=&amp;quot;4&amp;quot;  cellspacing=&amp;quot;0&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | &amp;lt;b&amp;gt;Ruby Type&amp;lt;/b&amp;gt;||&amp;lt;b&amp;gt; Java Type &amp;lt;/b&amp;gt;&lt;br /&gt;
   |-&lt;br /&gt;
   | assert_equal || assert_in_delta&lt;br /&gt;
   |-&lt;br /&gt;
   | assert_includes|| assert_instance_of&lt;br /&gt;
   |-&lt;br /&gt;
   | assert_match || assert_nil&lt;br /&gt;
   |-&lt;br /&gt;
   | assert_respond_to|| assert_same&lt;br /&gt;
   |-&lt;br /&gt;
   | assert_raises|| assert_send&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java. Thus mixing static and dynamic code combines the power of dynamic languages with the stability of static languages.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64848</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64848"/>
		<updated>2012-09-14T23:51:49Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /*  Driving Java from Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64846</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64846"/>
		<updated>2012-09-14T23:51:03Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /*  Driving Java from Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Ruby Type	Java Type&lt;br /&gt;
&amp;quot;foo&amp;quot;	java.lang.String&lt;br /&gt;
1	java.lang.Long&lt;br /&gt;
1.0	java.lang.Double&lt;br /&gt;
true, false	java.lang.Boolean&lt;br /&gt;
1	java.math.BigInteger&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
The JRuby interpreter combines Ruby's simplicity and ease of use with Java's extensive libraries and technologies, a potent blend that opens new possibilities for Ruby, Rails, and Java.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64826</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64826"/>
		<updated>2012-09-14T23:42:55Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion.For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64820</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64820"/>
		<updated>2012-09-14T23:41:32Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt; For e.g. Java, then the generic types are erased during compilation for backward compatibility. As a result for a dynamically types language like Ruby, there will be problems with type conversion. &lt;br /&gt;
For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64818</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64818"/>
		<updated>2012-09-14T23:40:50Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt;For e.g. Java, then the generic types are erased during compilation for backward compatibility. &lt;br /&gt;
As a result for a dynamically types language like Ruby, there will be problems with type conversion. &lt;br /&gt;
For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; - In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&amp;lt;br&amp;gt; - Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64815</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64815"/>
		<updated>2012-09-14T23:40:02Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
If the static oo makes use of generics.&amp;lt;br&amp;gt;For e.g. Java, then the generic types are erased during compilation for backward compatibility. &lt;br /&gt;
As a result for a dynamically types language like Ruby, there will be problems with type conversion. &lt;br /&gt;
For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&lt;br /&gt;
If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt; - In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&lt;br /&gt;
Inheritance&amp;lt;br&amp;gt; - Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64811</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64811"/>
		<updated>2012-09-14T23:39:23Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
If the static oo makes use of generics.&amp;lt;/br&amp;gt;For e.g. Java, then the generic types are erased during compilation for backward compatibility. &lt;br /&gt;
As a result for a dynamically types language like Ruby, there will be problems with type conversion. &lt;br /&gt;
For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&lt;br /&gt;
* &amp;lt;b&amp;gt;If you have a class name ambiguity between Java and Ruby.&amp;lt;/b&amp;gt; - In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&lt;br /&gt;
* &amp;lt;b&amp;gt;Inheritance&amp;lt;/b&amp;gt; - Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64804</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64804"/>
		<updated>2012-09-14T23:38:33Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* &amp;lt;b&amp;gt;If the static oo makes use of generics.&amp;lt;/b&amp;gt; - For e.g. Java, then the generic types are erased during compilation for backward compatibility. &lt;br /&gt;
As a result for a dynamically types language like Ruby, there will be problems with type conversion. &lt;br /&gt;
For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&lt;br /&gt;
* &amp;lt;b&amp;gt;If you have a class name ambiguity between Java and Ruby.&amp;lt;/b&amp;gt; - In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&lt;br /&gt;
* &amp;lt;b&amp;gt;Inheritance&amp;lt;/b&amp;gt; - Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64792</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64792"/>
		<updated>2012-09-14T23:36:33Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt;&lt;br /&gt;
For e.g. Java, then the generic types are erased during compilation for backward compatibility. &lt;br /&gt;
As a result for a dynamically types language like Ruby, there will be problems with type conversion. &lt;br /&gt;
For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt;&lt;br /&gt;
In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the         Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&lt;br /&gt;
Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64791</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w6 pp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w6_pp&amp;diff=64791"/>
		<updated>2012-09-14T23:35:56Z</updated>

		<summary type="html">&lt;p&gt;Psdeshp2: /* Difficulties in mixing static and dynamic oo code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p&amp;gt;Mixing static and dynamic [http://en.wikipedia.org/wiki/Object_oriented Object Oriented] code helps us to achieve a peaceful integration of static and dynamic aspect in the same language. This page will mention some difficulties when these two types of object orientation are mixed and then will give a practical example of this using [http://en.wikipedia.org/wiki/JRuby JRuby]. JRuby is a [http://en.wikipedia.org/wiki/Programming_language programming language] which is a mix of [http://en.wikipedia.org/wiki/Java Java] and [http://en.wikipedia.org/wiki/Ruby Ruby]. We will cover the different implementations of JRuby with examples. &amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Object oriented programming is a [http://en.wikipedia.org/wiki/Programming_paradigm programming paradigm] using &amp;quot;objects&amp;quot; – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. In static object orientation, this instantiation is static, that is the class to which an object belongs is defined before the execution of the code. This gives a strong binding of the objects, and ensures that the correct instance variables and methods are accessed by that object. In Dynamic object orientation, also known as interpreted object orientation, there is no fixed type. The type the object belongs to is determined during runtime, hence that gives additional flexibility. Static typing should be used where possible, dynamic typing when needed.&lt;br /&gt;
&lt;br /&gt;
== Difficulties in mixing static and dynamic oo code ==&lt;br /&gt;
&lt;br /&gt;
There can be some issues in mixing static and dynamic object oriented code. &lt;br /&gt;
&lt;br /&gt;
* If the static oo makes use of generics.&amp;lt;br&amp;gt;&lt;br /&gt;
   For e.g. Java, then the generic types are erased during compilation for backward compatibility. &lt;br /&gt;
   As a result for a dynamically types language like Ruby, there will be problems with type conversion. &lt;br /&gt;
   For example, if you have a Map&amp;lt;String,String&amp;gt;, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.&amp;lt;br&amp;gt;&lt;br /&gt;
* If you have a class name ambiguity between Java and Ruby.&amp;lt;br&amp;gt;&lt;br /&gt;
  In such a case, the class name will reference the Ruby construct within the Ruby code. For instance, if you import java.lang.Thread and then write JThread &amp;lt; Thread, JThread will in fact inherit the Ruby Thread object, not the         Java Thread. The solution is to use the full Java Class name, such as: JThread &amp;lt; java.lang.Thread&amp;lt;br&amp;gt;&lt;br /&gt;
* Inheritance&lt;br /&gt;
  Java classes can't inherit from a JRuby class. Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.&lt;br /&gt;
&lt;br /&gt;
== JRuby ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/JRuby JRuby] is the Ruby Programming Language on the [http://en.wikipedia.org/wiki/JVM JVM]. &lt;br /&gt;
Ruby is a reflective, dynamic, and interpreted object-oriented scripting language. JRuby is a Java programming language implementation of the Ruby language syntax with all the core libraries plus the  standard libraries. With JRuby, you get all of the advantages of Ruby plus access to the full range of Java platform functionality. This can be achieved in 2 flavors .&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Driving Ruby from Java&lt;br /&gt;
* Driving Java from Ruby&lt;br /&gt;
&lt;br /&gt;
Some examples where this integration can be done are: &lt;br /&gt;
&lt;br /&gt;
* From a JRuby script, you can call the Java platform Math library to access its powerful computational capabilities or call the Java platform Swing library to display a dialog box that requires end-user input before allowing the script to proceed. &amp;lt;br&amp;gt; &lt;br /&gt;
* You can use the [http://en.wikipedia.org/wiki/Scripting_for_the_Java_Platform JSR 223] Scripting APIs or the [http://en.wikipedia.org/wiki/Bean_Scripting_Framework Bean Scripting Framework (BSF)] APIs to call a JRuby script from within a Java application to, for example, invoke back-end processing scripts from a servlet to update or generate web content.   &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Advantages of JRuby ==&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Ruby ===&lt;br /&gt;
&lt;br /&gt;
* With JRuby you get the best of both worlds: Ruby applications and libraries, plus Java libraries. Anthreads, JRuby supports Unicode natively  &amp;lt;br&amp;gt;&lt;br /&gt;
* Code can be fully compiled ahead of time or just in time. &amp;lt;br&amp;gt;&lt;br /&gt;
* In addition to native you can access those libraries with Ruby syntax (or Java syntax, if you want).  &amp;lt;br&amp;gt;&lt;br /&gt;
* On average JRuby, runs 2 and a half times faster than Ruby, except at startup &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Advantages of JRuby over Java ===&lt;br /&gt;
&lt;br /&gt;
* Ruby is fun, beautiful, and powerful language &amp;lt;br&amp;gt;&lt;br /&gt;
* Ruby has features which are missing from Java &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Closure_(computer_science) Closure (blocks)] &amp;lt;br&amp;gt;&lt;br /&gt;
**Open classes &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Meta_programming Meta programming] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Duck_typing Duck-typing] &amp;lt;br&amp;gt;&lt;br /&gt;
**[http://en.wikipedia.org/wiki/Domain_Specific_Language Domain Specific Language] (DSL)&lt;br /&gt;
&lt;br /&gt;
== JRuby explained in details ==&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt; Driving Java from Ruby&amp;lt;/b&amp;gt;===&lt;br /&gt;
This involves calling Java methods from Ruby. This includes adding some java functionality in the Ruby code. The final code will be run on JVM. Ruby code can load and interact with Java Libraries. As a simple example we can use an ArrayList from java into Ruby code as below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require ‘java’&lt;br /&gt;
&lt;br /&gt;
list = java.util.ArrayList.new&lt;br /&gt;
&lt;br /&gt;
list &amp;lt;&amp;lt; ‘List of’&lt;br /&gt;
list &amp;lt;&amp;lt; 3 &lt;br /&gt;
list &amp;lt;&amp;lt; :assorted_items&lt;br /&gt;
&lt;br /&gt;
list.each do |item|&lt;br /&gt;
puts “#{item.class}: #{item}”&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of just requiring a specific class you can also require the entire package. This can be done as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
module JavaLangDemo&lt;br /&gt;
  include_package &amp;quot;java.lang&amp;quot;&lt;br /&gt;
  # alternately, use the #import method&lt;br /&gt;
  import &amp;quot;java.lang&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One has to be careful in doing this as with name conflicts in both Ruby and Java can lead to losing the Ruby functionality. For example if a File object is created using Java’s java.io.File class, then the Ruby constant File becomes useless -&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.io.File&lt;br /&gt;
newfile = File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
and then using - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
File.open('README', 'r') {|f| puts f.readline }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This will give the error - NoMethodError: private method `open' called for Java::JavaIo::File:Class&lt;br /&gt;
&lt;br /&gt;
This situation can be avoided by including the package in the module definition and then using that module scope to create using that File object.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
JRuby will forward any option to the underlying Java runtime if you preface it with -J.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;b&amp;gt;Driving Ruby from Java&amp;lt;/b&amp;gt;===&lt;br /&gt;
&lt;br /&gt;
There are three ways for using the JRuby Interpreter from Java namely, Embedding JRuby, using JSR 223 and the Bean Scripting Framework. &lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;Embedding JRuby&amp;lt;/b&amp;gt;====&lt;br /&gt;
Embed Core is the main embedding API that ships with JRuby. This API offers a great deal of interoperability. You can call a Ruby method, crunch the results in Java, and hand data back into Ruby. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import org.jruby.Ruby;&lt;br /&gt;
import org.jruby.RubyRuntimeAdapter;&lt;br /&gt;
import org.jruby.javasupport.JavaEmbedUtils; &lt;br /&gt;
&lt;br /&gt;
public class MyEmbedRubyExample {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
   	    // Create runtime instance&lt;br /&gt;
        Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());&lt;br /&gt;
        RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();&lt;br /&gt;
&lt;br /&gt;
        evaler.eval(runtime, &amp;quot;puts 1+2&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Shutdown and terminate instance&lt;br /&gt;
        JavaEmbedUtils.terminate(runtime);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To run the above code you need to include jruby.jar in the classpath. This jar is present in the JRuby installation in lib folder. The above example outputs &amp;quot;3&amp;quot; as expected.&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;JSR 223, Scripting for the Java Platform&amp;lt;/b&amp;gt;====&lt;br /&gt;
This provides an API framework for calling scripting code from within a Java application and passing data between the application and the script. These features make it possible to combine existing scripts with Java applications and to extend a Java application with general-purpose scripts that other Java applications can also use.&lt;br /&gt;
JSR 223 Scripting APIs are available in JDK 6 software, and by default, the APIs support the JavaScript programming language. With a little setup as described in the section JRuby Scripting Engine Setup, you can use the JSR 223 Scripting APIs with any JSR 223-compliant scripting engine such as JRuby.&lt;br /&gt;
&lt;br /&gt;
Steps:&lt;br /&gt;
Java integration with Java 6 will be using the standard scripting API (JSR223). A JRuby scripting engine already exists and is located at [https://scripting.dev.java.net here]&lt;br /&gt;
Download and unzip the collection of jars from the documents and files section of the site (jsr223-engines.tar.gz or jsr223-engines.zip).&lt;br /&gt;
Look in the uncompressed files for the jruby/build/jruby-engine.jar file.&lt;br /&gt;
Add this file to your classpath and then use the code below to access the engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import javax.script.*;&lt;br /&gt;
&lt;br /&gt;
public class jrubytry {&lt;br /&gt;
    public static void main(String[] args) throws Exception {&lt;br /&gt;
        ScriptEngineManager factory = new ScriptEngineManager();&lt;br /&gt;
&lt;br /&gt;
        // Create a JRuby engine.&lt;br /&gt;
        ScriptEngine engine = factory.getEngineByName(&amp;quot;jruby&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
        // Evaluate JRuby code from string.&lt;br /&gt;
        try {&lt;br /&gt;
            engine.eval(&amp;quot;puts('Hello')&amp;quot;);&lt;br /&gt;
        } catch (ScriptException exception) {&lt;br /&gt;
            exception.printStackTrace();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====&amp;lt;b&amp;gt;The Bean Scripting Framework (BSF)&amp;lt;/b&amp;gt;====&lt;br /&gt;
This is another way to call scripting code from within a Java application. &lt;br /&gt;
&lt;br /&gt;
The Bean Scripting Framework, when used with JRuby, will allow you to conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. To run a JRuby script using BSF, you must first copy the BSF.jar file into your JAVA_HOME/lib/ext/ folder. Then, try the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import org.jruby.Ruby.*;&lt;br /&gt;
import org.jruby.*;&lt;br /&gt;
import org.jruby.javasupport.bsf.*;&lt;br /&gt;
import org.apache.bsf.BSFException;&lt;br /&gt;
import org.apache.bsf.BSFManager;&lt;br /&gt;
{...}&lt;br /&gt;
JLabel mylabel = new JLabel();&lt;br /&gt;
BSFManager.registerScriptingEngine(&amp;quot;ruby&amp;quot;, &lt;br /&gt;
                                   &amp;quot;org.jruby.javasupport.bsf.JRubyEngine&amp;quot;, &lt;br /&gt;
                                   new String[] { &amp;quot;rb&amp;quot; });&lt;br /&gt;
&lt;br /&gt;
BSFManager manager = new BSFManager();&lt;br /&gt;
&lt;br /&gt;
/* Import an object using declareBean then you can access it in JRuby with $&amp;lt;name&amp;gt; */&lt;br /&gt;
 &lt;br /&gt;
manager.declareBean(&amp;quot;label&amp;quot;, mylabel, JFrame.class);&lt;br /&gt;
manager.exec(&amp;quot;ruby&amp;quot;, &amp;quot;(java)&amp;quot;, 1, 1, &amp;quot;$label.setText(\&amp;quot;This is a test.\&amp;quot;)&amp;quot;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Difficulties with JRuby ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Larger memory footprint and startup time&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A single JRuby instance needs more memory than a single Ruby instance, but in a typical production server environment with multiple mongrels, memory can be shared so that I expect a lower or at least equal memory usage in total. JRuby’s startup time is higher than MRI, but once the JVM has “warmed up” after a few minutes, it usually runs faster than MRI.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;No native C extension&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Due to the nature of Java, it is impossible to run any native extension. So there are several gems that don’t work since they rely on a C extension. However, there’s ongoing effort to create alternative gems that are compatible to JRuby. E.g. mongrel uses a native C extension, but if you install the mongrel gem using JRuby, it automatically installs a java-enhanced version.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;JRuby is not technically complete&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It’s told that there are cases where JRuby is not 100% compatible with MRI, however, I think these are very special cases; at least I didn’t encounter any problems yet. Big Frameworks like Rails are tested with JRuby, so I currently don’t expect any problems with it.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
[1] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html &amp;lt;br&amp;gt;&lt;br /&gt;
[2] http://java.sun.com/developer/technicalArticles/scripting/jruby/ &amp;lt;br&amp;gt;&lt;br /&gt;
[3] http://en.wikipedia.org/wiki/JRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[4] http://rubysource.com/learning-more-about-jruby-from-charles-nutter/ &amp;lt;br&amp;gt;&lt;br /&gt;
[5] https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby &amp;lt;br&amp;gt;&lt;br /&gt;
[6] http://media.pragprog.com/titles/jruby/embed.pdf &amp;lt;br&amp;gt;&lt;br /&gt;
[7] http://www.coderanch.com/t/461625/Ruby/JRuby-benefits &amp;lt;br&amp;gt;&lt;br /&gt;
[8] http://zargony.com/2008/09/26/why-i-m-starting-to-like-jruby-even-though-i-dislike-java &amp;lt;br&amp;gt;&lt;br /&gt;
[9] https://github.com/jruby/jruby/wiki/JavaIntegration#wiki-Java_6_using_JSR_223_Scripting &amp;lt;br&amp;gt;&lt;br /&gt;
[10] https://github.com/jruby/jruby/wiki/DirectJRubyEmbedding &amp;lt;br&amp;gt;&lt;br /&gt;
[11] Kutner, Joe (August 22, 2012), [http://research.microsoft.com/en-us/um/people/emeijer/Papers/RDL04Meijer.pdf Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages]&lt;br /&gt;
&lt;br /&gt;
== Further Reading ==&lt;br /&gt;
&lt;br /&gt;
Charles O Nutter, Thomas Enebo, Nick Sieger, Ola Bini, and Ian Dees, Using JRuby:Bringing Ruby to Java, 2011&lt;/div&gt;</summary>
		<author><name>Psdeshp2</name></author>
	</entry>
</feed>