Você está na página 1de 6

Proxy

Example: A highly simplified implementation of a proxy web server.


Intent:
Provide a surrogate or placeholder for another object to control access to it. Use an extra level of
indirection to support distributed, controlled, or intelligent access. Add a wrapper and delegation
to protect the real component from undue complexity.
Participants:
Subject - Interface implemented by the RealSubject and representing its services. The interface
must be implemented by the proxy as well so that the proxy can be used in any location where
the RealSubject can be used.
Proxy - Maintains a reference that allows the Proxy to access the RealSubject.
Implements the same interface implemented by the RealSubject so that the Proxy can be
substituted for the RealSubject. Controls access to the RealSubject and may be responsible for its
creation and deletion.
Other responsibilities depend on the kind of proxy.
RealSubject - the real object that the proxy represents.
Context: A client needs access to the services of another component. Direct access is technically possible,

but may not be the best approach.

Pattern Instance

Use Case Diagram

Class Diagram

Activity Diagram

Sequence Diagram

Communication Diagram

State Machine Diagram

Implementation:
CLASS 1:ApplicationClient.java
public class ApplicationClient {
public static void main(String[] args) {
Application application = new Application();
EmailServiceemailService =
application.locateEmailService();
emailService.sendMail("abc@gmail.com","Hello","A Text
Mail");
emailService.receiveMail("abc@gmail.com");}}
CLASS 2:Application.java
public class Application {
publicEmailServicelocateEmailService()
{
EmailServiceeS = new ProxyEmailService();
returneS;
}
}
CLASS 3:EmailService.java
public interface EmailService {
public void sendMail(String receive,Stringsubject,String text);
public void receiveMail(String receive);
}
CLASS 4:ProxyEmailService.java
public class ProxyEmailService implements EmailService {
privateRealEmailServiceemailService;
public void receiveMail(String receive)
{
if(emailService==null)
{
emailService=new RealEmailService();
emailService.receiveMail(receive);
}
public void sendMail(String receive, String subject, String text)
{
if(emailService==null)
{
emailService = new RealEmailService();
}
emailService.sendMail(receive,subject,text);
}

}
CLASS 5:RealEmailService.java
public class RealEmailService implements EmailService
{
public void sendMail(String receive,Stringsubject,String text)
{
System.out.println("Sending mail to '" + receive + "'" + "with Subject
'" + subject + "' " + " and message '" + text + "'");
}
public void receiveMail(String receive)
{
System.out.println("Receiving Mail from ' " + receive +"'");
}
}
OUTPUT:Sending mail to 'abc@gmail.com'with Subject 'Hello' and message 'A
Text Mail'
Receiving Mail from ' abc@gmail.com'

Você também pode gostar