SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Design Pattern-Proxy介紹
演說者:林政融
日期:2013/08/05
Agenda
 C#的Design Pattern
◦ Creational Patterns
◦ Structural Patterns
◦ Behavioral Patterns
 Design Pattern – Proxy
 Dynamic Proxy
C#的Design Pattern
Creational Patterns
 Abstract Factory Creates an instance
of several families of classes
 Builder Separates object construction
from its representation
 Factory Method Creates an instance
of several derived classes
 Prototype A fully initialized instance to
be copied or cloned
 Singleton A class of which only a
single instance can exist
Structural Patterns
 Adapter Match interfaces of different classes
 Bridge Separates an object’s interface from
its implementation
 Composite A tree structure of simple and
composite objects
 Decorator Add responsibilities to objects
dynamically
 Façade A single class that represents an
entire subsystem
 Flyweight A fine-grained instance used for
efficient sharing
 Proxy An object representing another
object
Behavioral Patterns
 Chain of Resp. A way of passing a request
between a chain of objects
 Command Encapsulate a command request
as an object
 Interpreter A way to include language
elements in a program
 Iterator Sequentially access the elements of a
collection
 Mediator Defines simplified communication
between classes
 Memento Capture and restore an object's
internal state
Behavioral Patterns(continue)
 Observer A way of notifying change to
a number of classes
 State Alter an object's behavior when
its state changes
 Strategy Encapsulates an algorithm
inside a class
 Template Method Defer the exact
steps of an algorithm to a subclass
 Visitor Defines a new operation to a
class without change
Design Pattern – Proxy
Definition
 Provide a surrogate or placeholder for
another object to control access to it.
UML class diagram
Sample Code
using System;
namespace DoFactory.GangOfFour.Proxy.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Proxy Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Create proxy and request a service
Proxy proxy = new Proxy();
proxy.Request();
// Wait for user
Console.ReadKey();
}
}
Sample Code(Subject)
/// <summary>
/// The 'Subject' abstract class
/// </summary>
abstract class Subject
{
public abstract void Request();
}
Sample Code(RealSubject)
/// <summary>
/// The 'RealSubject' class
/// </summary>
class RealSubject : Subject
{
public override void Request()
{
Console.WriteLine("Called
RealSubject.Request()");
}
}
Sample Code(Proxy)
/// <summary>
/// The 'Proxy' class
/// </summary>
class Proxy : Subject
{
private RealSubject _realSubject;
public override void Request()
{
// Use 'lazy initialization'
if (_realSubject == null)
{
_realSubject = new RealSubject();
}
_realSubject.Request();
}
}
}
Sample Code2
using System;
namespace DoFactory.GangOfFour.Proxy.RealWorld
{
/// <summary>
/// MainApp startup class for Real-World
/// Proxy Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Create math proxy
MathProxy proxy = new MathProxy();
// Do the math
Console.WriteLine("4 + 2 = " + proxy.Add(4, 2));
Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2));
Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2));
Console.WriteLine("4 / 2 = " + proxy.Div(4, 2));
// Wait for user
Console.ReadKey();
}
}
Sample Code2(IMath)
/// <summary>
/// The 'Subject interface
/// </summary>
public interface IMath
{
double Add(double x, double y);
double Sub(double x, double y);
double Mul(double x, double y);
double Div(double x, double y);
}
Sample Code2(Math)
/// <summary>
/// The 'RealSubject' class
/// </summary>
class Math : IMath
{
public double Add(double x, double y) { return x
+ y; }
public double Sub(double x, double y) { return x -
y; }
public double Mul(double x, double y) { return x *
y; }
public double Div(double x, double y) { return x /
y; }
}
Sample Code2(MathProxy)
/// <summary>
/// The 'Proxy Object' class
/// </summary>
class MathProxy : IMath
{
private Math _math = new Math();
public double Add(double x, double y)
{
return _math.Add(x, y);
}
public double Sub(double x, double y)
{
return _math.Sub(x, y);
}
public double Mul(double x, double y)
{
return _math.Mul(x, y);
}
public double Div(double x, double y)
{
return _math.Div(x, y);
}
}
}
Dynamic Proxy
Use of Static Proxy
 Situation: when do add, save the result
to DB
public double Add(double x, double y)
{
var result = _math.Add(x, y);
// Implement the method to save the
result to db
save(result);
return result;
}
Static Proxy
 Advantage: easy to revise the original
method
 Disadvantage: just only revise the
method that use the declared proxy
Dynamic Proxy(Interface)
public interface IProxyInvocationHandler {
Object Invoke( Object proxy,
MethodInfo method,
Object[] parameters );
}
Dynamic Proxy(Impl)
Public Object Invoke(Object proxy,
System.Reflection.MethodInfo method,
Object[] parameters)
{
Object retVal = null;
// is invoked, otherwise an exception is thrown indicating they
// do not have permission
if ( SecurityManager.IsMethodInRole( userRole, method.Name ) )
{
// The actual method is invoked
retVal = method.Invoke( obj, parameters );
} else
{
throw new IllegalSecurityException( "Invalid permission to invoke " +
method.Name );
}
return retVal;
}
Dynamic Proxy(Impl)
Public Object Invoke(Object proxy,
System.Reflection.MethodInfo method,
Object[] parameters)
{
Object retVal = null;
// is invoked, otherwise an exception is thrown indicating they
// do not have permission
if ( SecurityManager.IsMethodInRole( userRole, method.Name ) )
{
// The actual method is invoked
retVal = method.Invoke( obj, parameters );
} else
{
throw new IllegalSecurityException( "Invalid permission to invoke " +
method.Name );
}
return retVal;
}
Use of Dynamic Proxy
public interface ITest
{
void TestFunctionOne();
Object TestFunctionTwo( Object a, Object b );
}
public class TestImpl : ITest
{
public void TestFunctionOne()
{
Console.WriteLine( "In TestImpl.TestFunctionOne()" );
}
public Object TestFunctionTwo( Object a, Object b )
{
Console.WriteLine( "In TestImpl.TestFunctionTwo( Object a, Object b
)" );
return null;
}
Use of Dynamic
Proxy(continue)
public class TestBed
{
static void Main( string[] args )
{
ITest test = (ITest)SecurityProxy.NewInstance( new
TestImpl() );
test.TestFunctionOne();
test.TestFunctionTwo( new Object(), new Object() );
}
}
References
http://www.dofactory.com/Default.aspx
http://www.codeproject.com/Articles/5511/Dynam
ic-Proxy-Creation-Using-C-Emit

Weitere ähnliche Inhalte

Was ist angesagt?

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
Terry Yoast
 
iOS: Frameworks and Delegation
iOS: Frameworks and DelegationiOS: Frameworks and Delegation
iOS: Frameworks and Delegation
Jussi Pohjolainen
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
mtoppa
 

Was ist angesagt? (20)

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
iOS: Frameworks and Delegation
iOS: Frameworks and DelegationiOS: Frameworks and Delegation
iOS: Frameworks and Delegation
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
XML parsing using jaxb
XML parsing using jaxbXML parsing using jaxb
XML parsing using jaxb
 
Protocol in Swift
Protocol in SwiftProtocol in Swift
Protocol in Swift
 
Protocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftProtocol-Oriented Programming in Swift
Protocol-Oriented Programming in Swift
 
How Does Kubernetes Build OpenAPI Specifications?
How Does Kubernetes Build OpenAPI Specifications?How Does Kubernetes Build OpenAPI Specifications?
How Does Kubernetes Build OpenAPI Specifications?
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Solid principles
Solid principlesSolid principles
Solid principles
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
JAXB
JAXBJAXB
JAXB
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen Luong
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Design patterns illustrated 010PHP
Design patterns illustrated 010PHPDesign patterns illustrated 010PHP
Design patterns illustrated 010PHP
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 

Andere mochten auch

Output cacheattribute
Output cacheattributeOutput cacheattribute
Output cacheattribute
LearningTech
 
Powershell function
Powershell functionPowershell function
Powershell function
LearningTech
 
Will c# programming guild
Will c# programming guildWill c# programming guild
Will c# programming guild
LearningTech
 
Bacias Hidrográficas - Parte II
Bacias Hidrográficas - Parte IIBacias Hidrográficas - Parte II
Bacias Hidrográficas - Parte II
LCGRH UFC
 
Download-manuals-gis-gis methodology-manual
 Download-manuals-gis-gis methodology-manual Download-manuals-gis-gis methodology-manual
Download-manuals-gis-gis methodology-manual
hydrologywebsite1
 

Andere mochten auch (7)

Output cacheattribute
Output cacheattributeOutput cacheattribute
Output cacheattribute
 
Power shell
Power shellPower shell
Power shell
 
Powershell function
Powershell functionPowershell function
Powershell function
 
Will c# programming guild
Will c# programming guildWill c# programming guild
Will c# programming guild
 
Bacias Hidrográficas - Parte II
Bacias Hidrográficas - Parte IIBacias Hidrográficas - Parte II
Bacias Hidrográficas - Parte II
 
Geoloaction
GeoloactionGeoloaction
Geoloaction
 
Download-manuals-gis-gis methodology-manual
 Download-manuals-gis-gis methodology-manual Download-manuals-gis-gis methodology-manual
Download-manuals-gis-gis methodology-manual
 

Ähnlich wie Design pattern proxy介紹 20130805

Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
lcbj
 

Ähnlich wie Design pattern proxy介紹 20130805 (20)

Proxy design pattern
Proxy design patternProxy design pattern
Proxy design pattern
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
A resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleA resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangle
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
GradleFX
GradleFXGradleFX
GradleFX
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
WPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA AustriaWPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA Austria
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
 

Mehr von LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Design pattern proxy介紹 20130805

  • 2. Agenda  C#的Design Pattern ◦ Creational Patterns ◦ Structural Patterns ◦ Behavioral Patterns  Design Pattern – Proxy  Dynamic Proxy
  • 4. Creational Patterns  Abstract Factory Creates an instance of several families of classes  Builder Separates object construction from its representation  Factory Method Creates an instance of several derived classes  Prototype A fully initialized instance to be copied or cloned  Singleton A class of which only a single instance can exist
  • 5. Structural Patterns  Adapter Match interfaces of different classes  Bridge Separates an object’s interface from its implementation  Composite A tree structure of simple and composite objects  Decorator Add responsibilities to objects dynamically  Façade A single class that represents an entire subsystem  Flyweight A fine-grained instance used for efficient sharing  Proxy An object representing another object
  • 6. Behavioral Patterns  Chain of Resp. A way of passing a request between a chain of objects  Command Encapsulate a command request as an object  Interpreter A way to include language elements in a program  Iterator Sequentially access the elements of a collection  Mediator Defines simplified communication between classes  Memento Capture and restore an object's internal state
  • 7. Behavioral Patterns(continue)  Observer A way of notifying change to a number of classes  State Alter an object's behavior when its state changes  Strategy Encapsulates an algorithm inside a class  Template Method Defer the exact steps of an algorithm to a subclass  Visitor Defines a new operation to a class without change
  • 9. Definition  Provide a surrogate or placeholder for another object to control access to it.
  • 11. Sample Code using System; namespace DoFactory.GangOfFour.Proxy.Structural { /// <summary> /// MainApp startup class for Structural /// Proxy Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Create proxy and request a service Proxy proxy = new Proxy(); proxy.Request(); // Wait for user Console.ReadKey(); } }
  • 12. Sample Code(Subject) /// <summary> /// The 'Subject' abstract class /// </summary> abstract class Subject { public abstract void Request(); }
  • 13. Sample Code(RealSubject) /// <summary> /// The 'RealSubject' class /// </summary> class RealSubject : Subject { public override void Request() { Console.WriteLine("Called RealSubject.Request()"); } }
  • 14. Sample Code(Proxy) /// <summary> /// The 'Proxy' class /// </summary> class Proxy : Subject { private RealSubject _realSubject; public override void Request() { // Use 'lazy initialization' if (_realSubject == null) { _realSubject = new RealSubject(); } _realSubject.Request(); } } }
  • 15. Sample Code2 using System; namespace DoFactory.GangOfFour.Proxy.RealWorld { /// <summary> /// MainApp startup class for Real-World /// Proxy Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Create math proxy MathProxy proxy = new MathProxy(); // Do the math Console.WriteLine("4 + 2 = " + proxy.Add(4, 2)); Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2)); Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2)); Console.WriteLine("4 / 2 = " + proxy.Div(4, 2)); // Wait for user Console.ReadKey(); } }
  • 16. Sample Code2(IMath) /// <summary> /// The 'Subject interface /// </summary> public interface IMath { double Add(double x, double y); double Sub(double x, double y); double Mul(double x, double y); double Div(double x, double y); }
  • 17. Sample Code2(Math) /// <summary> /// The 'RealSubject' class /// </summary> class Math : IMath { public double Add(double x, double y) { return x + y; } public double Sub(double x, double y) { return x - y; } public double Mul(double x, double y) { return x * y; } public double Div(double x, double y) { return x / y; } }
  • 18. Sample Code2(MathProxy) /// <summary> /// The 'Proxy Object' class /// </summary> class MathProxy : IMath { private Math _math = new Math(); public double Add(double x, double y) { return _math.Add(x, y); } public double Sub(double x, double y) { return _math.Sub(x, y); } public double Mul(double x, double y) { return _math.Mul(x, y); } public double Div(double x, double y) { return _math.Div(x, y); } } }
  • 20. Use of Static Proxy  Situation: when do add, save the result to DB public double Add(double x, double y) { var result = _math.Add(x, y); // Implement the method to save the result to db save(result); return result; }
  • 21. Static Proxy  Advantage: easy to revise the original method  Disadvantage: just only revise the method that use the declared proxy
  • 22. Dynamic Proxy(Interface) public interface IProxyInvocationHandler { Object Invoke( Object proxy, MethodInfo method, Object[] parameters ); }
  • 23. Dynamic Proxy(Impl) Public Object Invoke(Object proxy, System.Reflection.MethodInfo method, Object[] parameters) { Object retVal = null; // is invoked, otherwise an exception is thrown indicating they // do not have permission if ( SecurityManager.IsMethodInRole( userRole, method.Name ) ) { // The actual method is invoked retVal = method.Invoke( obj, parameters ); } else { throw new IllegalSecurityException( "Invalid permission to invoke " + method.Name ); } return retVal; }
  • 24. Dynamic Proxy(Impl) Public Object Invoke(Object proxy, System.Reflection.MethodInfo method, Object[] parameters) { Object retVal = null; // is invoked, otherwise an exception is thrown indicating they // do not have permission if ( SecurityManager.IsMethodInRole( userRole, method.Name ) ) { // The actual method is invoked retVal = method.Invoke( obj, parameters ); } else { throw new IllegalSecurityException( "Invalid permission to invoke " + method.Name ); } return retVal; }
  • 25. Use of Dynamic Proxy public interface ITest { void TestFunctionOne(); Object TestFunctionTwo( Object a, Object b ); } public class TestImpl : ITest { public void TestFunctionOne() { Console.WriteLine( "In TestImpl.TestFunctionOne()" ); } public Object TestFunctionTwo( Object a, Object b ) { Console.WriteLine( "In TestImpl.TestFunctionTwo( Object a, Object b )" ); return null; }
  • 26. Use of Dynamic Proxy(continue) public class TestBed { static void Main( string[] args ) { ITest test = (ITest)SecurityProxy.NewInstance( new TestImpl() ); test.TestFunctionOne(); test.TestFunctionTwo( new Object(), new Object() ); } }