Domain Driven Design Implementation Patterns and Considerations in.NET.
Patterns in.NET - ACCU 2002 - slides (mostly ) by Michael Stal, Senior Principal Engineer SIEMENS...
-
Upload
britton-mccoy -
Category
Documents
-
view
215 -
download
2
Transcript of Patterns in.NET - ACCU 2002 - slides (mostly ) by Michael Stal, Senior Principal Engineer SIEMENS...
Patterns in .NETPatterns in .NET- ACCU 2002 -- ACCU 2002 -
slides (mostly slides (mostly ) by) byMichael Stal, Senior Principal EngineerMichael Stal, Senior Principal EngineerSIEMENS AG, Dept. CT SE 2SIEMENS AG, Dept. CT SE 2E-Mail: E-Mail: mailto:[email protected]:[email protected]: Web: http://www.stal.dehttp://www.stal.de
Markus Voelter, CTO, MATHEMA AGMarkus Voelter, CTO, MATHEMA [email protected]://www.voelter.de
Markus Voelter/Michael Stal – Patterns in .NETFolie 2
Goal of the PresentationGoal of the Presentation
Understand some design decisions Understand some design decisions in the .NET frameworkin the .NET framework
Use of Patterns to describe Use of Patterns to describe architectural aspects of systemsarchitectural aspects of systems
NOT: Introduction to .NETNOT: Introduction to .NET
Markus Voelter/Michael Stal – Patterns in .NETFolie 3
AgendaAgenda
MotivationMotivation Architectural AspectsArchitectural Aspects
• Web-ServicesWeb-Services• .NET Remoting.NET Remoting• CollectionsCollections• Forms and ControlsForms and Controls• ThreadingThreading• InteropInterop
SummarySummary LiteratureLiterature
Markus Voelter/Michael Stal – Patterns in .NETFolie 4
MotivationMotivation
.NET represents a completely new .NET represents a completely new infrastructure for Windows infrastructure for Windows development and a new development and a new LifestyleLifestyle..
Class Loader
IL to NativeCompilers
CodeManager
GarbageCollector
Security Engine Debug Engine
Type Checker Exception Manager
Thread Support COM Marshaler
Base Class Library Support
System
System.Data System.Xml
System.Web
Globalization
Diagnostics
Configuration
Collections
Resources
Reflection
Net
IO
Threading
Text
ServiceProcess
Security
Design
ADO
SQLTypes
SQL
XPath
XSLT
RuntimeInteropServices
Remoting
Serialization
Serialization
Configuration SessionState
Caching Security
ServicesDescription
Discovery
Protocols
UIHtmlControls
WebControls
System.Drawing
Imaging
Drawing2D
Text
Printing
System.Windows.Forms
Design ComponentModelCLR
Markus Voelter/Michael Stal – Patterns in .NETFolie 5
Motivation (cont‘d)Motivation (cont‘d)
Compared to „legacy“ Windows Compared to „legacy“ Windows development, .NET simplifies matters development, .NET simplifies matters significantly. significantly.
But .NET is voluminous, it‘s easy to lose But .NET is voluminous, it‘s easy to lose sight of the big picturesight of the big picture
For efficient .NET development, it‘s not For efficient .NET development, it‘s not enough to know the APIs, you need to enough to know the APIs, you need to understand the internal architecture of .NETunderstand the internal architecture of .NET
This presentation tries to answer not the This presentation tries to answer not the howhow, but the , but the whywhy from an architectural from an architectural viewpoint.viewpoint.
Markus Voelter/Michael Stal – Patterns in .NETFolie 6
What is a pattern?What is a pattern?
A Pattern…A Pattern…
… … represents a concrete solution represents a concrete solution (template) for recurring problems in the (template) for recurring problems in the respective domain. respective domain.
… … takes into account the forces that takes into account the forces that drive the solution.drive the solution.
… … documents expertisedocuments expertise
... specifies concepts on top of classes ... specifies concepts on top of classes and objects (such as collaborations, and objects (such as collaborations, interactions) interactions)
… … provides a common vocabulary and a provides a common vocabulary and a common understanding of conceptscommon understanding of concepts
... Adresses specific quality properties of ... Adresses specific quality properties of the solution.the solution.
ObserverProblem
Solution
House1 Door_A; Window_1a Window_1b ...
is presented asdepends ondepends on
Subject
attachdetachnotifysetDatagetData
s->getData()
Observer
update
ConcreteObserver
updatedoSomething
state = X;notify();
stateobserverList
for all observersin observerList do notify();
*
Subject Observer 1 Observer 2
attach(this)
attach(this)
setDatanotify
update
getData
update
getData
Markus Voelter/Michael Stal – Patterns in .NETFolie 7
Web ServicesWeb Services
Markus Voelter/Michael Stal – Patterns in .NETFolie 8
The Web is the The Web is the Computer Computer
We need an infrastructure, that • allows web-based communication
among components• provides location transparency• allows to add, remove or to change
services dynamically • and keeps all the gory details hidden
from the programmer
Markus Voelter/Michael Stal – Patterns in .NETFolie 9
Idea: Web ServicesIdea: Web Services A Web service represents a unit of business, application, or
system functionality that can be accessed over the Web (Internet, Intranet, or Extranet)• they are accessible over the Web• they expose an XML interface• they can be registered and located through a Web service registry• they communicate using XML messages over standard Web protocols• they support loosely-coupled connections between systems
Web services focus on business-to-consumer, business-to-business, department-to-department, peer-to-peer interactions.
Consumers of these services may be humans or application programs or other Web services.
In theory, it doesn‘t matter what technologies are used to build Web services, because all Web service environments can interoperate using XML protocols. (Sun Microsystems)
Markus Voelter/Michael Stal – Patterns in .NETFolie 10
Broker-based Broker-based architecturearchitecture
marshal
unmarshal
receive_result
service(proxy)
Client-side Proxy
marshal
unmarshal
dispatch
receive_request
Server-side Proxy
start_up
main_loop
service(impl.)
Service
call_service_p
start_task
Client
calls*
1
calls
*
1
Message exchange*
Message exchange *1
register_server
find_server
establish_communication
Broker1
Markus Voelter/Michael Stal – Patterns in .NETFolie 11
Broker: Dynamics Broker: Dynamics
method (proxy)locate_server
server port
receive_request
marshal
unmarshal
dispatchmethod (impl.)
result
marshalreceive_result
unmarshal
result
start_upregister_service
BrokerClient Proxy Server ProxyClient Server
assigned port
Markus Voelter/Michael Stal – Patterns in .NETFolie 12
The Proxy Pattern forms The Proxy Pattern forms the basisthe basis
Solution
Provide a placeholder for the object through which clients can access it
A Service implements the object which is not directly accessible.
A Proxy represents the Service and ensures the correct access to it. The Proxy offers the same interface as the Service.
Clients use the Proxy to get access to the Service.
Proxy
service
Client
Service
service1 1
AbstractService
service
Markus Voelter/Michael Stal – Patterns in .NETFolie 13
Proxy: DynamicsProxy: Dynamics
ServiceProxyClient
service
service
pre-processing:
marshaling
post-processing:
unmarshaling
Markus Voelter/Michael Stal – Patterns in .NETFolie 14
Step 1: The transport Step 1: The transport protocolprotocol
A protocol defines syntax, semantics A protocol defines syntax, semantics and flow of messages among peers.and flow of messages among peers.
For a web-based protocol, we need:For a web-based protocol, we need:• HTTP and other internet protocols as HTTP and other internet protocols as
transport layertransport layer• „„self-describing data representation format“ self-describing data representation format“
Kurz: XML. Kurz: XML. • In Details: every invocation and its response In Details: every invocation and its response
is rendered as an XML document sent over is rendered as an XML document sent over the wire using HTTP et. al. the wire using HTTP et. al.
• Welcome in the world of SOAP.Welcome in the world of SOAP.
Markus Voelter/Michael Stal – Patterns in .NETFolie 15
Step 1 – ExampleStep 1 – Example
Example for a SOAP Message:
<soap:Envelope><soap:Header>
<transaction><soap:mustUnderstandstand=„true“ xmlns=„http://tx.com“>
<id> 12345678 </id></transaction>
<soap:Header><soap:Body>
<m:getPhoneNumber><theName> Bill Gates </theName>
<m:/getPhoneNumber></soap:Body>
</soap:Envelope>
SOAP messages are bracketed by envelopes
headers are optional
this feature must be supported by the receiver
message body
Markus Voelter/Michael Stal – Patterns in .NETFolie 16
Step 2: Description Step 2: Description LanguageLanguage We need a description of what a We need a description of what a
webservice provideswebservice provides• The available operations and their signature, The available operations and their signature,
including complex typesincluding complex types• How and where a service can be accessedHow and where a service can be accessed
We also use XML for this purpose in the We also use XML for this purpose in the form of WSDL, the Web Service form of WSDL, the Web Service Description Language (WSDL).Description Language (WSDL).
Warning: WSDL does not describe any Warning: WSDL does not describe any semantics (as with practically all interface semantics (as with practically all interface definition languages)definition languages)
Markus Voelter/Michael Stal – Patterns in .NETFolie 17
Step 3: How to find the Step 3: How to find the servicesservices
Client
Web Service
Descriptionof Web Service
(WSDL)
UDDI
1. search for web service
2. return service URL
4. send request using SOAP over HTTP
5. forward request to service
6. return result7. send result using
SOAP over HTTP
Web Server
3. read service description
UDDI is a global UDDI is a global registryregistry
Registration Registration possible at any possible at any nodenode
Registrations Registrations replicated at daily replicated at daily basisbasis
Common SOAP Common SOAP protocol usedprotocol used
Publisher API
Inquiry API
Markus Voelter/Michael Stal – Patterns in .NETFolie 18
UDDI as a universal UDDI as a universal registryregistry
White Pages Yellow Pages Green Pages
• Registry acessible by name
• Listing of all service providers including details
• Contact information (Webservices, Telephone,…)
• Mercantile directory
• Lookups based on several taxonomies (location, kind of service, domain, …)
• Points to White Pages
• Information on the business model of the business
• Technical details about the provided web services
• Information on business processes
Markus Voelter/Michael Stal – Patterns in .NETFolie 19
.NET provides tools... .NET provides tools...
The tools generate glue code to The tools generate glue code to „connect“ to the web middleware:„connect“ to the web middleware:• Client Proxies um den Client mit dem Dienst Client Proxies um den Client mit dem Dienst
zu verbinden.zu verbinden.• Server Proxies zur nahtlosen Server Proxies zur nahtlosen
Dienstintegration.Dienstintegration.• also generate WSDL from server objectsalso generate WSDL from server objects
WSDL
ClientProxy
ServerProxy
Markus Voelter/Michael Stal – Patterns in .NETFolie 20
Example in .NETExample in .NET
A simple WebserviceA simple Webservicenamespace EuroDMConversion {
public class Converter: System.Web.Services.WebService {[WebMethod]public double DM_to_Euro(double value){
return value / 1.95583;}[WebMethod]public double Euro_to_DM(double value){
return value * 1.95583;}
}}
Markus Voelter/Michael Stal – Patterns in .NETFolie 21
Example in .NET Example in .NET (cont‘d.)(cont‘d.)
A Demo-Client:A Demo-Client:private void buttonClk(object sender, System.EventArgs e){
if (textBox1.Text.Equals("")) {textBox1.Text = "0";return;
}localhost.Service1 s1 = new localhost.Service1();textBox2.Text = s1.DM_to_Euro(double.Parse(textBox1.Text));
}
Markus Voelter/Michael Stal – Patterns in .NETFolie 22
.NET Remoting.NET Remoting
Markus Voelter/Michael Stal – Patterns in .NETFolie 23
What is.NET RemotingWhat is.NET Remoting
.NET Remoting is the true successor .NET Remoting is the true successor to DCOM.to DCOM.
A framework to allow (remote) A framework to allow (remote) applications to communicateapplications to communicate
Flexibility: Almost everything can Flexibility: Almost everything can be exchanged or extended be exchanged or extended (Protokoll, Marshaler, ...).(Protokoll, Marshaler, ...).
Contexts as in COM+ are supported!Contexts as in COM+ are supported!• With a With a veryvery simple API! simple API!
Markus Voelter/Michael Stal – Patterns in .NETFolie 24
Remoting from 10.000 ftRemoting from 10.000 ft
Application Domain B
Client
Formatters
Channels
Envoy Sinks
Real Proxy
Transparent Proxy
Servant
Formatters
Channels
Server Context Sinks
Object Context Sinks
Network
Application Domain A
Markus Voelter/Michael Stal – Patterns in .NETFolie 25
An ExampleAn Example
The Remote Object:The Remote Object:public class Grid : System.MarshalByRefObject {
const int LENGTH = 10;double [,] matrix = new double[LENGTH,LENGTH];public int Length { get { return LENGTH; } }public double this[int i1, int i2] { set { if (OutOfBounds(i1,i2)) throw new ArgumentException(); else matrix[i1,i2] = value; } get { if (OutOfBounds(i1,i2)) throw new ArgumentException(); else return matrix[i1,i2]; }}bool OutOfBounds(int i1, int i2) { return (i1 < 0) || (i1 >= LENGTH) || (i2 < 0) || (i2 >= LENGTH) ? true : false;}
}
Markus Voelter/Michael Stal – Patterns in .NETFolie 26
An Example cont‘dAn Example cont‘d
The Server:The Server:class Server{ static void Main(string[] args) {
TcpServerChannel ch = new TcpServerChannel(8888);ChannelServices.RegisterChannel(ch);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Grid), "Grid",
WellKnownObjectMode.Singleton);while(true); // loop forever
}}
Markus Voelter/Michael Stal – Patterns in .NETFolie 27
An Example cont‘dAn Example cont‘d
A Client:A Client:class Client { static void Main(string[] args) { ChannelServices.RegisterChannel(new TcpClientChannel()); Grid myGrid = (Grid)Activator.GetObject(typeof(Grid),
"tcp://localhost:8888/Grid"); if (myGrid == null) {
Console.WriteLine("Could not connect!");return;
} for (int i = 0; i < myGrid.Length; i++) {
for (int j = 0; j < myGrid.Length; j++) {myGrid[i,j] = (double)(i*10 + j);
} } }}
Markus Voelter/Michael Stal – Patterns in .NETFolie 28
Design of .NET RemotingDesign of .NET Remoting
.NET Remoting is also based on the .NET Remoting is also based on the Broker patternBroker pattern
marshal
unmarshal
receive_result
service(proxy)
Client-side Proxy
marshal
unmarshal
dispatch
receive_request
Server-side Proxy
start_up
main_loop
service(impl.)
Service
call_service_p
start_task
Client
calls*
1
calls
*
1
Message exchange*
Message exchange *1
register_server
find_server
establish_communication
Broker1
Markus Voelter/Michael Stal – Patterns in .NETFolie 29
Addition of Context Addition of Context informationinformation (Call) Contexts are data items that (Call) Contexts are data items that
are automatically transported with are automatically transported with a remote invocation.a remote invocation.• It is not part of the method signatureIt is not part of the method signature• Client and Server both have access to the Client and Server both have access to the
data, typically inside „technical frameworks“data, typically inside „technical frameworks“• Typically, security or transaction information Typically, security or transaction information
is transferred in contextsis transferred in contexts
How can we make sure context data How can we make sure context data is transparently added to remote is transparently added to remote invocations in .NET? invocations in .NET?
Markus Voelter/Michael Stal – Patterns in .NETFolie 30
Solutions: InterceptorsSolutions: Interceptors
Introduce interceptors that can be attached to a system for handling particular events. Whenever an event occurs, the associated interceptors get automatically called:
Runtime represents the framework to which we like to attach interceptors. It is responsible for managing and calling interceptors.
Concrete Interceptors implement the event handler for the system specific events they have subscribed for.
Environment contains information about the event and allows to modify the system behavior after interceptor completion.
The container is responsible for registering its interceptors with the runtime.
Runtime
runEventLoopattachInterceptormanage interceptors
Abstract Interceptor
handleEvent
Environment
Concrete Interceptor
handleEvent*
callbackcallback
provideprovide
Container
attachattach
Markus Voelter/Michael Stal – Patterns in .NETFolie 31
DynamicsDynamics
ApplicationRuntime
InterceptorcreaterunEventLoop
attachInterceptor
Place interceptor in internal interceptor map
event
Look for registered interceptors
Envcreate
Env
handleEvent
Markus Voelter/Michael Stal – Patterns in .NETFolie 32
Chaining of InterceptorsChaining of Interceptors
We need a mechanism to chain We need a mechanism to chain several interceptors so that each several interceptors so that each gets a chance to do somethinggets a chance to do something
A tight coupling of sender and A tight coupling of sender and receiver should be avoidedreceiver should be avoided
How can we achieve this?How can we achieve this? Solution: Chain of Responsibility Solution: Chain of Responsibility
Pattern:Pattern:aHandlersuccessor
aHandlerrequest
requestaHandlersuccessor
request
Markus Voelter/Michael Stal – Patterns in .NETFolie 33
Avoidance of Avoidance of DependenciesDependencies
.NET Remoting should be .NET Remoting should be independent ofindependent of• The transport protocolThe transport protocol• Which marshalling strategy is usedWhich marshalling strategy is used
In a Broker-Architecture, the In a Broker-Architecture, the proxies are responsible for the proxies are responsible for the communication.communication.
How can the proxies be decoupled How can the proxies be decoupled from this responsibility?from this responsibility?
Markus Voelter/Michael Stal – Patterns in .NETFolie 34
Forwarder-ReceiverForwarder-Receiver
Solution: Additional componentsSolution: Additional components
Forwarder
marshaldeliversendMessage
Peer 1
service
Peer 2
service
Forwarder
marshaldeliversendMessage
Receiver
receiveunmarshalreceiveMessage
Receiver
receiveunmarshalreceiveMessage
Here
There
Markus Voelter/Michael Stal – Patterns in .NETFolie 35
Forwarder-Receiver Forwarder-Receiver (cont‘d)(cont‘d)
DynamicsDynamics
Receiver 1Forwarder 1Peer 1
sendMsg
deliver
unmarshal
Forwarder 2 Peer 2Receiver 2
recvMsg
receivemarshal
Message
Markus Voelter/Michael Stal – Patterns in .NETFolie 36
Plug and Play Plug and Play
In .NET Remoting Channels and In .NET Remoting Channels and Formatters should be exchangableFormatters should be exchangable• TCP-Channels and HTTP ChannelsTCP-Channels and HTTP Channels• SOAP Formatter and binary FormatterSOAP Formatter and binary Formatter
How is pluggability reached without How is pluggability reached without consequences for the upper layers?consequences for the upper layers?
Markus Voelter/Michael Stal – Patterns in .NETFolie 37
Solution: Strategy Solution: Strategy PatternPattern
Encapsulate each strategy as a separate object:
Strategy declares an interface common to all supported implementation.
Concrete Strategies implement the strategy interface for a specific implementation.
Context offers a service to clients and is configured with a concrete implementation.
Strategy
dispatch
ConcreteStrategy
dispatch
Context
Markus Voelter/Michael Stal – Patterns in .NETFolie 38
Strategy in .NET Strategy in .NET RemotingRemoting The Formatters in .NET implement die the The Formatters in .NET implement die the
IRemotingFormatter interface• Serialize() • Deserialize(). .
A Formater Sink Provider implements the A Formater Sink Provider implements the interface interface IServerChannelSinkProvider (Server) (Server) or or IClientChannelSinkProvider (Client).(Client).
A sending channel implemens A sending channel implemens IChannelSender (Forwarder) and a receiving channel (Forwarder) and a receiving channel implements implements IChannelReceiver (Receiver).(Receiver).• A channel can also play both roles by implementing both A channel can also play both roles by implementing both
interfacesinterfaces
Markus Voelter/Michael Stal – Patterns in .NETFolie 39
Asynchronous Asynchronous CommunicationCommunication
.NET and .NET Remoting technically .NET and .NET Remoting technically only support synchronous only support synchronous invocationsinvocations• Caller has to wait until an invocation returnsCaller has to wait until an invocation returns• It cannot do anything else in the meantime It cannot do anything else in the meantime
(in that same threat, that is!)(in that same threat, that is!)
Markus Voelter/Michael Stal – Patterns in .NETFolie 40
Solution: Asynchronousity Solution: Asynchronousity using message layerusing message layer
Introduce intermediary queues between senders and receivers :
Queues are used to store messages persistently. They cooperate with other queues for message routing.
Messages are objects send from a sender to a receiver.
A sender sends messages, while a receiver receives them.
A Message API is provided for senders and receivers to send/recv messages.
Queue
storeforwardremove
Sender
Receiver
Message
Queue
storeforwardremove
Message API
Message API
<<write>>
<<read>>
<<send>>
<<recv>>
<<route>>
Markus Voelter/Michael Stal – Patterns in .NETFolie 41
DynamicsDynamics
Message APISender
send Message
Messagecreate
Queue Queue
storeMessage
forwardMessage
Receiver
create
Message API
receive
receive
Message
Message
read
Markus Voelter/Michael Stal – Patterns in .NETFolie 42
The developer‘s viewThe developer‘s view
Developers prefer a (synchronous) RPC-Developers prefer a (synchronous) RPC-style modelstyle model
We separate calls into two messagesWe separate calls into two messages• RequestsRequests contain in/in-out arguments contain in/in-out arguments• ResultsResults contain out/inout arguments and results contain out/inout arguments and results
Callbacks or polling technique to receive Callbacks or polling technique to receive results (futures)results (futures)
Markus Voelter/Michael Stal – Patterns in .NETFolie 43
Developer‘s view Developer‘s view (cont‘d)(cont‘d)
Client
Proxy(Recorder) Queue Proxy
(Player)
Client
1. method()
2. enqueue 3. dequeue
4. method() 5. result
6. enqueue7. dequeue
8. return
Markus Voelter/Michael Stal – Patterns in .NETFolie 44
Asynchronous Asynchronous Communication in .NETCommunication in .NET
First, a synchronous call using a First, a synchronous call using a delegatedelegate
public delegate int WorkDelegate(string s);
public int DoWork(string s) {Console.WriteLine("Doing work ...{0}", s);return 42;
}
public void Test() {WorkDelegate w = new WorkDelegate(DoWork);int i = w("Synchronous Hallo"); // synch callConsole.WriteLine("Result = {0}", i.ToString());...
Markus Voelter/Michael Stal – Patterns in .NETFolie 45
Asynchronous Asynchronous Communication in .NET Communication in .NET (cont‘d)(cont‘d) Now asynchronously with pollingNow asynchronously with polling
public void Test() {// call it asynchronouslyIAsyncResult ar = w.BeginInvoke( "Asynchronous Hallo with Polling", null,
null);ar.AsyncWaitHandle.WaitOne(); // wait until readyi = w.EndInvoke(ar);Console.WriteLine("Result = {0}", i.ToString());
}
Markus Voelter/Michael Stal – Patterns in .NETFolie 46
Asynchronous Asynchronous Communication in .NET Communication in .NET (cont‘d)(cont‘d) Now Asynch with callbackNow Asynch with callback
private void CallCompleted(IAsyncResult ar) {WorkDelegate w = (WorkDelegate)
((AsyncResult)ar).AsyncDelegate;int i = w.EndInvoke(ar);Console.WriteLine("Result = {0}", i.ToString());
}
public void Test() {// call it asynchronously with callbackw.BeginInvoke("Asynchronous Hallo with Callback",
new AsyncCallback(CallCompleted), null);}
Markus Voelter/Michael Stal – Patterns in .NETFolie 47
Problem: Remote object Problem: Remote object Activation Activation
Resources such as remote objects Resources such as remote objects should only be instantiated when should only be instantiated when they are actually required.they are actually required.
There needs to be a way to activate There needs to be a way to activate objects when they are needed!objects when they are needed!
So: How do we implement an So: How do we implement an activation strategy?activation strategy?
Markus Voelter/Michael Stal – Patterns in .NETFolie 48
Solution: Activator Solution: Activator PatternPattern
Integrate activation code for automatically starting up server implementations. Provide necessary information in tables:
Upon incoming requests the Activator looks up whether a target object is already active. If the object is not running it activates the implementation.
The Activation Table stores associations between services and their physical location.
The Client uses the Activator to get service access.
A Service implements a specific type of functionality that it provides to clients.
Activator
(de)activategetServiceregisterunregisteronShutdown
Activation Table
insertEntryremoveEntrylookupEntrychangeEntry
Service
serviceshutdown
Client
Get ServiceGet Service
useService
Markus Voelter/Michael Stal – Patterns in .NETFolie 49
DynamicsDynamics
Activator Client Activ. Table
getService
Implementationactivate
lookupEntry
[not active]
changeEntryobject
service
result
port
onShutdown
changeEntry
Markus Voelter/Michael Stal – Patterns in .NETFolie 50
Deactivation in .NETDeactivation in .NET
Question: How do I make sure that Question: How do I make sure that activated remote objects are activated remote objects are eventually deactivated (freed)?eventually deactivated (freed)?
Answer: Lease-PatternAnswer: Lease-Pattern• The object is only active for a specific period The object is only active for a specific period
of time of time • When the lease expires, the object is freed.When the lease expires, the object is freed.• The release is renewed based on certain The release is renewed based on certain
criteria:criteria:- A method invocation by the clientA method invocation by the client- ……
Markus Voelter/Michael Stal – Patterns in .NETFolie 51
MetainformationMetainformation
In dynamic environments, not all In dynamic environments, not all information can be made available information can be made available at compile timeat compile time
(Runtime)Tools like generators and (Runtime)Tools like generators and marshallers need to look deep marshallers need to look deep inside the details of types.inside the details of types.
How can these informations be How can these informations be made available?made available?
Markus Voelter/Michael Stal – Patterns in .NETFolie 52
Solution: Reflection Solution: Reflection PatternPattern
Provide type information through meta objects and allow clients to find and use this meta information:
Meta Objects provide information and functionality about existing base objects.
The MetaObject Protocol is responsible for creating and retrieving Meta Objects.
Base Objects implement the application functionality.
Clients access Meta Objects to dynamically invoke base functionality.
MetaObject
metaInformationmetaService
Client
Abstract BaseObject
getMetaObject
MetaObject Protocolaccessesaccesses
Concrete BaseObject
service
11
11
access and use meta information
use servicesuse services
Markus Voelter/Michael Stal – Patterns in .NETFolie 53
DynamicsDynamics
Client MetaObject BaseObject
analyze meta info and invoke meta services
MetaObject
BaseObjectgetMetaObjectgetMetaObject
metaInformationmetaInformation
metaServicemetaServiceInvocation
serviceservice
service execution
Result
Markus Voelter/Michael Stal – Patterns in .NETFolie 54
Reflection in .NETReflection in .NET
Component InterfaceComponent Interface
The Client:The Client:Assembly a = Assembly.LoadFrom("Component.dll");Type [] allTypes = a.GetTypes();Type t = allTypes[0];object o = Activator.CreateInstance(t);MethodInfo mi = t.GetMethod("algorithm");double d = (double) mi.Invoke(o, new object[]{21.0});
public abstract class ComponentBase {public abstract double algorithm(double d);
};
Markus Voelter/Michael Stal – Patterns in .NETFolie 55
Event HandlingEvent Handling
In many parts of the .NET In many parts of the .NET framework, events have to be framework, events have to be propagated from one component to propagated from one component to another.another.• GUI/Web controls need to send events to GUI/Web controls need to send events to
user defined operationsuser defined operations• (Asynchronous) events among remote (Asynchronous) events among remote
componentscomponents• Starting threads upon the „start“ signalStarting threads upon the „start“ signal
Markus Voelter/Michael Stal – Patterns in .NETFolie 56
Solution: Observer-Solution: Observer-PatternPattern GoalGoal
Description of dependencies among objects so that Description of dependencies among objects so that all are notified if a specific object changesall are notified if a specific object changes
ApplicabilityApplicability• If the change of one object is relevant to othersIf the change of one object is relevant to others• Decoupling the changing subject from their observersDecoupling the changing subject from their observers
StructureStructure Subject
attach()detach()notify()
Observer
update()
ConcreteObserver
update()
ConcreteSubject
getState()setState()
observers
while (e.hasMoreElements()) Observer o = (Observer) e.nextElement(); o.update(this));
state = newState;notify();
subject
Markus Voelter/Michael Stal – Patterns in .NETFolie 57
Observer in .NETObserver in .NET
The „observed“ object, whose The „observed“ object, whose changes are of interest to otherschanges are of interest to others
In .NET, delegates are used here!In .NET, delegates are used here!
public class Subject {public delegate void Notify();public event Notify OnNotify;public void DoSomething() {
// now create an eventif (null != OnNotify) {
Console.WriteLine("Subject fires event");OnNotify();
}}
}
Markus Voelter/Michael Stal – Patterns in .NETFolie 58
Observer in .NET Observer in .NET (cont‘d)(cont‘d) The observerThe observer
class ObserverDemo {class Observer {
public Observer(Subject s) {s.OnNotify += new Subject.Notify(TellMe);
}public void TellMe() {
// react on change}
}static void Main(string[] args) {
Subject s = new Subject();Observer o1 = new Observer(s);Observer o2 = new Observer(s); ...
}}
Markus Voelter/Michael Stal – Patterns in .NETFolie 59
CollectionsCollections
Markus Voelter/Michael Stal – Patterns in .NETFolie 60
Implementations of Implementations of ContainersContainers
Containers (or collections) are Containers (or collections) are essential for all kinds of applications.essential for all kinds of applications.
A container contains several other A container contains several other objectsobjects• As a setAs a set• As an ordered listAs an ordered list• As a dictionaryAs a dictionary
How can we iterate over these How can we iterate over these elements independent of the concrete elements independent of the concrete container type (set, list, container type (set, list, dictionary,...)?dictionary,...)?
Markus Voelter/Michael Stal – Patterns in .NETFolie 61
Solution: IteratorsSolution: Iterators
GoalGoal• A way to iterate over the elements of a container A way to iterate over the elements of a container
without revealing details about its inner structurewithout revealing details about its inner structure Applicability Applicability
• Common iteration interface for all kinds of containersCommon iteration interface for all kinds of containers• There might be different ways of iterating over the There might be different ways of iterating over the
contentscontents Structure Structure
Iterator
ConcreteIterator
Aggregate
ConcreteAggregate
Markus Voelter/Michael Stal – Patterns in .NETFolie 62
Iterators in .NETIterators in .NET
Iterators are integrated into .NET Iterators are integrated into .NET (C#)(C#)
The Container-Implementor has to The Container-Implementor has to implement specific interfacesimplement specific interfaces
foreach (Element e in container) { ... } // CLIENT
IEnumerator {object Current { get; }bool MoveNext();void Reset();
}IEnumerable {
IEnumerator GetEnumerator();}
Markus Voelter/Michael Stal – Patterns in .NETFolie 63
Forms and ControlsForms and Controls
Markus Voelter/Michael Stal – Patterns in .NETFolie 64
ControlsControls
There are different controls in .NETThere are different controls in .NETControl
RichControl
ScrollableControl
FormatControl
TreeView
ContainerControl
Panel
Label
TextBoxBase
TextBox
RichTextBox
Markus Voelter/Michael Stal – Patterns in .NETFolie 65
ProblemProblem
Controls can either be simple Controls can either be simple (atomic) controls or they can be (atomic) controls or they can be complex controls themselves made complex controls themselves made up of several other controlsup of several other controls
But all controls (simple and But all controls (simple and complex) should behave complex) should behave consistently and provide a common consistently and provide a common interface to clients.interface to clients.
How can this be achieved?How can this be achieved?
Markus Voelter/Michael Stal – Patterns in .NETFolie 66
Solution: CompositeSolution: Composite
GoalGoal• Allow the recursive contruction of complex objects Allow the recursive contruction of complex objects
from simple objectsfrom simple objects Applicability Applicability
• Complex objects are made Complex objects are made up of simpler objectsup of simpler objects
• Part-Whole-Hierarchies Part-Whole-Hierarchies need to be implementedneed to be implemented
Structure Structure
Component
operation()children()
Composite
add()remove()children()
Leaf children
Markus Voelter/Michael Stal – Patterns in .NETFolie 67
Hierarchical Event Hierarchical Event ManagementManagement
Within such a control-composite, Within such a control-composite, events must be handled.events must be handled.
A subcontrol might want to A subcontrol might want to delegate event handling to ist delegate event handling to ist containercontainer
How can this be done?How can this be done? Again: Chain-of-Responsibility:Again: Chain-of-Responsibility:
aHandlersuccessor
aHandlerrequest
requestaHandlersuccessor
request
Markus Voelter/Michael Stal – Patterns in .NETFolie 68
ThreadingThreading
Markus Voelter/Michael Stal – Patterns in .NETFolie 69
ThreadingThreading
Multithreaded programming is Multithreaded programming is supported in .NETsupported in .NET
A Warning: Thread programming is A Warning: Thread programming is by no means trivial – even if the API by no means trivial – even if the API seems simple!!seems simple!!• Race conditionsRace conditions• DeadlocksDeadlocks• ....
It was thus very important for It was thus very important for the .NET designers to take care of a the .NET designers to take care of a couple of things.couple of things.
Markus Voelter/Michael Stal – Patterns in .NETFolie 70
Scoped LockingScoped Locking
Problem
We need to protect “critical regions” in an object from concurrent access that would destroy the object’s consistency
Locks that protect a critical region need to be acquired and later on released.
It is hard to guarantee that the locks are released in all execution paths through an operations.
GetElement
SetElement
TopoTree
class MyInventory {public void insert() { // Critical section. lock.Acquire()(); // Do something ... if (error) return; // Bad! // Do something ... lock.Release(); }private LockType lock;}
Markus Voelter/Michael Stal – Patterns in .NETFolie 71
Scoped Locking (cont’d)Scoped Locking (cont’d)
Solution
Using an guard that acquires a certain type of lock and guarantees to release it eventually:
Scoped Locking idiom.
(In C++ it can be implemeted by the users – in Java and C# it needs to be part of the language because of the garbage collection strategies…)
class MyInventory {public void insert() { // Critical section. lock(obj) { // Do something ...
return; // no problem! } }}
Markus Voelter/Michael Stal – Patterns in .NETFolie 72
Thread Safe InterfaceThread Safe Interface
Problem
To protect objects, often all operations are synchronized.
If an operation calls another operation on the same instance within a protected area, a deadlock occurs.
GetElement
SetElement
TopoTree
class MyInventory {public void f1() {
lock(this) {f2();
}}public void f2() {
lock(this) {// dead?
}}
}
Markus Voelter/Michael Stal – Patterns in .NETFolie 73
Thread Safe Interface Thread Safe Interface (cont‘d)(cont‘d)
Solution
Interface operations (accessed by external clients) are protected and delegate to their internal implementation operations.
The private internal operations are unprotected and call each other.
This is implicitly done in Java and C#.
class MyInventory {public void f1() {
lock(this) {f1_i();
}}public void f2() {
lock(this) {f2_i();
}}private void f1_i() {
f2_i();}private void f2_i() {
//}
}
Markus Voelter/Michael Stal – Patterns in .NETFolie 74
COM+ InteropCOM+ Interop
How can .NET components be used How can .NET components be used as COM+ components, and vice as COM+ components, and vice versa?versa?
Markus Voelter/Michael Stal – Patterns in .NETFolie 75
Adapter aka WrapperAdapter aka Wrapper
GoalGoalConverting an interface into another, expected oneConverting an interface into another, expected one
Applicability Applicability • Exisiting interface is not suitableExisiting interface is not suitable• You want to adapt objects and thus make them You want to adapt objects and thus make them
reusablereusable StrukturStruktur
ClientTargetInterface
operation()
Adaptee
adapteeOperation()
Adapter
operation()
adaptee
Markus Voelter/Michael Stal – Patterns in .NETFolie 76
Wrapper in .NETWrapper in .NET
RCW (Runtime Callable Wrapper), to RCW (Runtime Callable Wrapper), to import COM objects into .NET.import COM objects into .NET.
CCW (COM Callable Wrapper) for CCW (COM Callable Wrapper) for the other directionthe other direction
Warning: You also need to import Warning: You also need to import type information, such as TYPELIBs.type information, such as TYPELIBs.
COM+Objekt
RCWClient
Markus Voelter/Michael Stal – Patterns in .NETFolie 77
SummarySummary
Patterns describe expert solution for Patterns describe expert solution for recurring problemsrecurring problems
Patterns are useful for the development Patterns are useful for the development of new systems, but alsoof new systems, but also
For „Reverse Engineering“, as you might For „Reverse Engineering“, as you might have seen in this presentationhave seen in this presentation
Only by understanding the internal Only by understanding the internal architecture of .NET can you implement architecture of .NET can you implement efficiently. Patterns can help here!efficiently. Patterns can help here!
This presentation could only scratch the This presentation could only scratch the surfacesurface
You can mine more patterns yourself!!You can mine more patterns yourself!!
Markus Voelter/Michael Stal – Patterns in .NETFolie 78
The Gang Of Four BookThe Gang Of Four Book
The Gang Of Four BookThe Gang Of Four Book
is the first, and still the most popular is the first, and still the most popular pattern book. It contains 23 general pattern book. It contains 23 general
purpose design patterns and idioms forpurpose design patterns and idioms for
• Object creation: Object creation: Abstract FactoryAbstract Factory, , Builder Factory MethodBuilder Factory Method, , PrototypePrototype, , and and SingletonSingleton
• Structural Decomposition: Structural Decomposition: CompositeCompositeandand Interpreter Interpreter
• Organization of Work: Organization of Work: CommandCommand,,MediatorMediator, and , and Chain of ResponsibilityChain of Responsibility
• Service Access: Service Access: ProxyProxy, , FacadeFacade, and , and IteratorIterator
• Extensibility: Extensibility: DecoratorDecorator and and VisitorVisitor• Variation: Variation: BridgeBridge, , StrategyStrategy, , StateState,,
and and Template MethodTemplate Method• Adaptation: Adaptation: AdapterAdapter• Resource Handling: Resource Handling: MementoMemento and and
FlyweightFlyweight• Communication:Communication: Observer Observer
Markus Voelter/Michael Stal – Patterns in .NETFolie 79
POSA1: A System Of POSA1: A System Of PatternsPatterns
A A System Of PatternsSystem Of Patterns
is the first volume of the POSA series. is the first volume of the POSA series. It contains 17 general purpose It contains 17 general purpose
architectural patterns, design patterns architectural patterns, design patterns and idioms for:and idioms for:
• Structural Decomposition: Structural Decomposition: LayersLayers, , BlackboardBlackboard Pipes and FiltersPipes and Filters, and , and Whole PartWhole Part
• Distributed Systems: Distributed Systems: BrokerBroker, , Forwarder-Forwarder-ReceiverReceiver and and Client-Dispatcher-Server Client-Dispatcher-Server
• Interactive Systems: Interactive Systems: Model-View-Model-View-Controller Controller and and Presentation-Abstraction-ControlPresentation-Abstraction-Control
• Adaptive Systems: Adaptive Systems: MicrokernelMicrokernel, , ReflectionReflection
• Organization of Work: Organization of Work: Master SlaveMaster Slave• Service Access: Service Access: ProxyProxy • Resource Management: Resource Management: Counted PointerCounted Pointer
Command ProcessorCommand Processor, , View HandlerView Handler• Communication:Communication: Publisher-Subscriber Publisher-Subscriber
Markus Voelter/Michael Stal – Patterns in .NETFolie 80
POSA2: Patterns For POSA2: Patterns For Concurrent and Networked Concurrent and Networked ObjectsObjects
Patterns For Concurrent And Networked Patterns For Concurrent And Networked ObjectsObjects
is the second volume of the POSA series. is the second volume of the POSA series. It contains 17 architectural patterns, It contains 17 architectural patterns,
design patterns and idioms for design patterns and idioms for concurrent, and networked systems:concurrent, and networked systems:
• Service Access and Configuration: Service Access and Configuration: Wrapper Facade, Component Configurator, Wrapper Facade, Component Configurator, Interceptor and Extension InterfaceInterceptor and Extension Interface
• Event Handling: Reactor, Event Handling: Reactor, Proactor,Asynchronous completion Token Proactor,Asynchronous completion Token and Acceptor-Connector and Acceptor-Connector
• Synchronization: Scoped Locking, Double-Synchronization: Scoped Locking, Double-Checked Locking, Strategized Locking, and Checked Locking, Strategized Locking, and Thread-Safe InterfaceThread-Safe Interface
• Concurrency: Active Object, Monitor Concurrency: Active Object, Monitor Object, Object, Leader/Followers, Thread-Specific Storage Leader/Followers, Thread-Specific Storage Half-Sync/Half-AsyncHalf-Sync/Half-Async
Markus Voelter/Michael Stal – Patterns in .NETFolie 81
Server Component Server Component PatternsPatterns
Server Component PatternsServer Component PatternsAnother book in Wiley’s pattern series to Another book in Wiley’s pattern series to be published in mid 2002. It focuses on be published in mid 2002. It focuses on
component infrastructures on the server.component infrastructures on the server.
• Core Architecture ElementsCore Architecture Elements• Component Implementation Building Component Implementation Building
BlocksBlocks• Container Implementation BasicsContainer Implementation Basics• A Component and its EnvironmentA Component and its Environment• Identifying and Managing InstancesIdentifying and Managing Instances• Remote Access to ComponentsRemote Access to Components• More Container ImplementationMore Container Implementation• Component DeploymentComponent Deployment
• See also See also www.servercomponentpatterns.orgwww.servercomponentpatterns.org