viernes, 15 de noviembre de 2019

Proxy pattern example

Proxy pattern
Index
Proxy pattern
Includes code that you can download from GitHub

Theory

The proxy pattern Provide a surrogate or placeholder for another object to control access to it.

One reason for controlling access to an object is to defer the full cost of its creation and initialization until we actually need to use it.

In this example we have simulated a remote communication as you will see.

The UML model is

Figure-1

Code of the application

Comm Interface

package com.patterns.proxy;

public interface Comm {
	public String receive();
	public boolean reset();


}


CommImpl Class

package com.patterns.proxy;

public class CommImpl implements Comm {
private static int INFOLENGTH = 10;
private boolean isAlive = false;
private String information;
public String receive() {
	// TODO Auto-generated method stub
	if(isAlive) mockCall();
	return read();
}
public boolean reset() {
	if(isAlive) isAlive=false;
	else isAlive = true;
	return isAlive;
}
public String read() {
	// TODO Auto-generated method stub
	if(isAlive)
	information = this.generateInfo();
	return information;
}
 void mockCall() {
	try {
		Thread.sleep(500);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

String generateInfo() {
	StringBuffer sb = new StringBuffer();
	String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	for(int i=0;i

CommProxy Class

package com.patterns.proxy;

public class CommProxy implements Comm{

	private static CommImpl comm;
    private boolean isAlive;
    
	public CommProxy() {
		comm = new CommImpl();
	}
	
	public String receive() {
	   
		if(isAlive) /*new information arrived */
			return comm.receive(); 
		else
			return "NO NEW INFORMATION=" + comm.receive();
	}

	public boolean reset() {
		isAlive = comm.reset();
		return isAlive;
		// TODO Auto-generated method stub
		
	}


	
}


App Class

ckage com.patterns.proxy;

/**
 
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    	String message;
        CommProxy proxy = new CommProxy();
        
        proxy.reset();
        message = proxy.receive();
        System.out.println("Mess-1"+ message);
        proxy.reset();
        message = proxy.receive();
        System.out.println("Mess-2"+ message);
        proxy.reset();
        message = proxy.receive();
        System.out.println("Mess-3"+ message);
    }
}


No hay comentarios :

Publicar un comentario