SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11Ben Abdallah Helmi
 
Test Data Builder Pattern
Test Data Builder PatternTest Data Builder Pattern
Test Data Builder PatternAlan Parkinson
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design PatternsRobert Brown
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity FrameworkJames Johnson
 
Dependency Injection with Unity Container
Dependency Injection with Unity ContainerDependency Injection with Unity Container
Dependency Injection with Unity ContainerMindfire Solutions
 
Advance java session 11
Advance java session 11Advance java session 11
Advance java session 11Smita B Kumar
 
Creating data with the test data builder pattern
Creating data with the test data builder patternCreating data with the test data builder pattern
Creating data with the test data builder patternAlan Parkinson
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
An Introduction to Domain Driven Design in PHP
An Introduction to Domain Driven Design in PHPAn Introduction to Domain Driven Design in PHP
An Introduction to Domain Driven Design in PHPChris Renner
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsRichie Rump
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Dependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And UnityDependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And Unityrainynovember12
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 

What's hot (20)

SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11
 
Test Data Builder Pattern
Test Data Builder PatternTest Data Builder Pattern
Test Data Builder Pattern
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
J2EE jsp_03
J2EE jsp_03J2EE jsp_03
J2EE jsp_03
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design Patterns
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
Dependency Injection with Unity Container
Dependency Injection with Unity ContainerDependency Injection with Unity Container
Dependency Injection with Unity Container
 
Advance java session 11
Advance java session 11Advance java session 11
Advance java session 11
 
Core Data
Core DataCore Data
Core Data
 
Creating data with the test data builder pattern
Creating data with the test data builder patternCreating data with the test data builder pattern
Creating data with the test data builder pattern
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
An Introduction to Domain Driven Design in PHP
An Introduction to Domain Driven Design in PHPAn Introduction to Domain Driven Design in PHP
An Introduction to Domain Driven Design in PHP
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Dependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And UnityDependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And Unity
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 

Similar to C# Design Pattern Proxy介紹

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 Symfony2Hugo Hamon
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
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 triangleAkihito Koriyama
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Savio Sebastian
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
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 AustriaRainer Stropek
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projetolcbj
 
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 & WebpackCodifly
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 

Similar to C# Design Pattern Proxy介紹 (20)

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
 
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
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 

More from LearningTech

More from 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
 

Recently uploaded

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 

Recently uploaded (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 

C# Design Pattern Proxy介紹

  • 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() ); } }