Вы находитесь на странице: 1из 157

Patrones de Diseo Diseo

Contenido
 

Introduccin Principales patrones Observer Singleton Command Adapter Template Method Iterator

Composite State Decorator Facade Proxy Abstract Factory

Introduccin
Que son patrones de diseo? diseo?


Combinacin de dos cosas:


Una descripcin de un problema Una descripcin de su solucin

Los patrones de diseo se usan en el mundo real


Diseo de puentes, edificios, etc

La solucin no describe los detalles de una implementacin en particular. Es como una plantilla: Describe todos los elementos y caractersticas de la solucin en lenguaje genrico y forma la base para muchas implementaciones

El patrn Observer
Definicin


Define a one-to-many dependency between one-toobjects so that when one object changes state, all its dependents are notified and updated automatically.

El patrn Observer
Modelo
Knows its observers. Any number of Observer objects may observe a subject Provides an interface for attaching and detaching Observer objects. Defines an updating interface for objects that should be notified of changes in a subject.

Stores state of interest to ConcreteObserver Sends a notification to its observers when its state changes

Maintains a reference to a ConcreteSubject object Stores state that should stay consistent with the subject's Implements the Observer updating interface to keep its state consistent with the subject's

El patrn Observer
Ejemplo de Cdigo - Subject
abstract class Stock { protected string symbol; protected double price; private ArrayList investors = new ArrayList(); public Stock( string symbol, double price ) { this.symbol = symbol; this.price = price; } public void Attach( Investor investor ) { investors.Add( investor ); } public void Detach( Investor investor ) { investors.Remove( investor ); } public void Notify() { foreach( Investor i in investors ) i.Update( this ); } public double Price { get{ return price; } set{ price = value; Notify(); } } public string Symbol { get{ return symbol; } set{ symbol = value; } } }

El patrn Observer
Ejemplo de Cdigo Concrete Subject

class IBM : Stock { // Constructor public IBM( string symbol, double price ) : base( symbol, price ) {} }

El patrn Observer
Ejemplo de Cdigo - Observer

interface IInvestor { // Methods void Update( Stock stock ); }

El patrn Observer
Ejemplo de Cdigo Concrete Observer
class Investor : IInvestor { // Fields private string name; private string observerState; private Stock stock; // Constructors public Investor( string name ) { this.name = name; } // Methods public void Update( Stock stock ) { Console.WriteLine( "Notified investor {0} of {1}'s " + "change to {2:C}", name, stock.Symbol, stock.Price ); } // Properties public Stock Stock { get{ return stock; } set{ stock = value; } } }

El patrn Observer
Ejemplo de Cdigo Cliente Test
Investor s = new Investor( "Sorros" ); Investor b = new Investor( "Berkshire" ); // Create IBM IBM ibm = new ibm.Attach( s ibm.Attach( b // Change ibm.Price ibm.Price ibm.Price ibm.Price stock and attach investors IBM( "IBM", 120.00 ); ); );

price, which notifies investors = 120.10; = 121.00; = 120.50; = 120.75;

Patrn Observer

El patrn Observer
Ejercicio In the process of of writing an application, suppose I get a new requirement to take the following actions whenever a new customer is entered into the system:
Send a welcome e-mail to the customer eVerify the customers address with the post office

All these all of the requirements? Will things change in the future? TASK: TASK: Apply the Observer Pattern to the Case Study How well does this work if I get a new requierement?
For example what If I need to send a letter with coupons to customers located with 20 miles of one of the company stores?

El patrn Singleton
Definicin


Singleton assures that there is one and only one instance of a class, and provides a global point of access to it
There are any number of cases in programming where you need to make sure that there can be one and only one instance of a class. For example, your system can have only one window manager or print spooler, or a single point of access to adatabase engine. Your PC might have several serial ports but there can only be one instance of COM1.

El patrn Singleton
Modelo

Defines an Instance operation that lets clients access its unique instance. Instance is a class operation. Responsible for creating and maintaining its own unique instance

El patrn Singleton
Ejemplo de Cdigo - Spooler
Public Class Spooler Private Shared mInstanceFlag As Spooler Private Sub New() End Sub Public Shared Function GetSpooler() As Spooler If mInstanceFlag Is Nothing Then mInstanceFlag = New Spooler End If Return mInstanceFlag End Function End Class

El patrn Singleton
Ejemplo de Cdigo Client Test

Dim sp1 As Spooler = Spooler.GetSpooler Dim sp2 As Spooler = Spooler.GetSpooler If (sp1.Equals(sp2)) Then MessageBox.Show("The same instance") Else MessageBox.Show("Not the same instance") End If

El patrn Singleton
Ejemplo de cdigo - Multithreading


El ejemplo anterior no contempla la posibilidad de dos "threads" (hilos de ejecucin) que, al mismo tiempo, pidan el mtodo GetSpooler(), por primera vez. Si as sucediera, podra suceder que estos dos hilos de ejecucin, cada cual por su parte, encuentre en "Nothing" a la instancia interna, y hagan cada uno un "new", creando dos instancias. Se puede mejorar el ejemplo usando un objeto Mutex

El patrn Singleton
Ejemplo de cdigo - Multithreading


Mutex
Es un mecanismo de sincronizacin que otorga acceso exclusivo al recurso compartido a solo un thread. Si un thread adquiere el mutex, el segundo thread que desea adquirir el mutex es suspendido hasta que el primer thread libere el mutex. Puede utlizar el mtodo WaitOne() para requerir la propiedad de un mutex El thread debe llamar al mtodo ReleaseMutex() para liberar la propiedad del mutex

El patrn Singleton
Ejemplo de Cdigo Spooler Multithread
Imports System.Threading Public Class Spooler Private Shared mInstanceFlag As Spooler Private Shared mSync As New Mutex Private Sub New() End Sub Public Shared Function GetSpooler() As Spooler mSync.WaitOne() Try If mInstanceFlag Is Nothing Then mInstanceFlag = New Spooler End If Finally mSync.ReleaseMutex() End Try Return mInstanceFlag End Function End Class

Patrn Singleton

El patrn Command
Definicin


Encapsulate a request as an object and gives it a known public interface. It lets you give the client the ability to make requests without knowing anything about the actual action that will be performed and allows you to change that action without affecting the client program in any way.

El patrn Command
Usos


Command objects are useful for implementing:


MultiMulti-level undo. If all user actions in a program are implemented as command objects, the program can keep a stack of the most recently executed commands. When the user wants to undo a command, the program simply pops the most recent command object and executes its undo() method. Wizards. The command object is created when the wizard is first displayed. Each wizard page stores its GUI changes in the command object, so the object is populated as the user progresses.

El patrn Command
Usos GUI buttons and menu items. In addition to the ability to perform the desired command, an Action may have an associated icon, keyboard shortcut, tooltip text, and so on. A toolbar button or menu item component may be completely initialized using only the Action object. Macro recording. If all user actions are represented by command objects, a program can record a sequence of actions simply by keeping a list of the command objects as they are executed. It can then "play back" the same actions by executing the same command objects again in sequence.

El patrn Command
Modelo
Creates a ConcreteCommand object and sets its receiver Defines a binding between a Receiver object and an action implements Execute by invoking the corresponding operation(s) on Receiver Knows how to perform the operations associated with carrying out the request asks the command to carry out the request Declares an interface for executing an operation

El patrn Command
Ejemplo de Cdigo - Receiver
Public Class Calculator Private mTotal As Integer = 0 Public Sub Operation(ByVal operator As Char, _ ByVal operand As Integer) Select Case operator Case "+"c : mTotal += operand Case "-"c : mTotal -= operand Case "*"c : mTotal *= operand Case "/"c : mTotal /= operand End Select MessageBox.Show(String.Format( _ "Total = {0} (operacion realizada {1} {2})", _ mTotal, operator, operand)) End Sub End Class

El patrn Command
Ejemplo de Cdigo - Command

Public MustInherit Class Command Public MustOverride Sub Execute() Public MustOverride Sub UnExecute() End Class

El patrn Command
Ejemplo de Cdigo Concrete Command
Public Class CalculatorCommand Inherits Command Private mOperator As Char Private mOperand As Integer Private mCalculator As Calculator Public Sub New(ByVal oCalculator As Calculator, ByVal operator As Char, _ ByVal operand As Integer) Me.mCalculator = oCalculator Me.mOperator = operator Me.mOperand = operand End Sub Public Overrides Sub Execute() mCalculator.Operation(mOperator, mOperand) End Sub Public Overrides Sub UnExecute() mCalculator.Operation(Undo(mOperator), mOperand) End Sub Private Function Undo(ByVal operator As Char) As Char Dim cUndo As Char = " "c Select Case mOperator Case "+"c : cUndo = "-" Case "-"c : cUndo = "+" Case "*"c : cUndo = "/" Case "/"c : cUndo = "*" End Select Return cUndo End Function End Class

El patrn Command
Ejemplo de Cdigo - Invoker
Public Class User Private mCalculator As New Calculator Private mCommands As New ArrayList Private mCurrent As Integer = 0 Public Sub Redo(ByVal levels As Integer) MessageBox.Show(String.Format("Redo {0} levels", levels)) For i As Integer = 0 To levels - 1 If mCurrent < mCommands.Count - 1 Then CType(mCommands(mCurrent), Command).Execute() mCurrent += 1 End If Next End Sub Public Sub Undo(ByVal levels As Integer) MessageBox.Show(String.Format("Undo {0} levels", levels)) For i As Integer = 0 To levels - 1 If mCurrent > 0 Then mCurrent -= 1 CType(mCommands(mCurrent), Command).UnExecute() End If Next End Sub Public Sub Compute(ByVal operator As Char, ByVal operand As Integer) Dim oCommand As New CalculatorCommand(mCalculator, operator, operand) oCommand.Execute() mCommands.Add(oCommand) mCurrent += 1 End Sub End Class

El patrn Command
Ejemplo de Cdigo Client Test
Dim oUser As New User oUser.Compute("+"c, 100) oUser.Compute("-"c, 50) oUser.Compute("*"c, 10) oUser.Compute("/"c, 2) oUser.Undo(4) oUser.Redo(3)

Patrn Command

El patrn Command
Ejercicio


Mouse clicks on list box items and on radio buttons also constitute commands. Clicks on multiselect list boxes could also be represented as commands. Design a program including these features. A lottery system uses a random number generator constrained to integers between 1 and 50. The selections are made at intervals selected by a random timer. Each selection must be unique. Design command patterns to choose the winning numbers each week.

El patrn Adapter
Definicin


The Adapter pattern is used to convert the programming interface of one class into that of another. We use adapters whenever we want unrelated classes to work together in a single program. The concept of an adapter is thus pretty simple:
We write a class that has the desired interface and then make it communicate with the class that has a different interface.

El patrn Adapter
Definicin


There are two ways to do this:


By inheritance (class adapters) We derive a new class from the nonconforming one and add the methods we need to make the new derived class match the desired interface. By object composition (object adapters) The other way is to include the original class inside the new one and create the methods to translate calls within the new class.

El patrn Adapter
Modelo
collaborates with objects conforming to the Target interface defines the domainspecific interface that Client uses

adapts the interface Adaptee to the Target interface

defines an existing interface that needs adapting

El patrn Adapter
Ejemplo de Cdigo The Adaptee
Public Class FrenchRestaurant Public Sub OrderFromMenu(ByVal Request) Console.WriteLine(Request & _ "? Oui, monsieur. Bon appetit. ") End Sub End Class

El patrn Adapter
Ejemplo de Cdigo The Target

Public Interface FoodOrderer Sub Order(ByVal Request) End Interface

El patrn Adapter
Ejemplo de Cdigo The Adapter
Public Class FrenchFoodOrderer Inherits FrenchRestaurant Implements FoodOrderer Public Sub Order(ByVal Request) _ Implements FoodOrderer.Order OrderFromMenu(Request) End Sub End Class

El patrn Adapter
Ejemplo de Cdigo The Client
Public Class FastFoodOrderer Implements FoodOrderer Public Sub Order(ByVal Request) _ Implements FoodOrderer.Order Console.WriteLine(Request & " coming up. ") End Sub End Class

El patrn Adapter
Ejemplo de Cdigo Client TEST
Dim objFoodOrderer As FoodOrderer Console.WriteLine("Let's order from the Fast Food restaurant: ") objFoodOrderer = New FastFoodOrderer() objFoodOrderer.Order("1 Cheeseburger") Console.WriteLine( _ "Now let's order some French food from their fancy restaurant menu: ") objFoodOrderer = New FrenchFoodOrderer() objFoodOrderer.Order("Moules Mariniere") MessageBox.Show("Click OK to end")

Patrn Adapter

El patrn Adapter
Ejercicio
1.

Crear un Assembly conteniendo una clase que permita agregar, actualizar y eliminar un Producto de la BD
Establezca su propia nomenclatura

2.

3.

Crear otro Assembly con una Interfase IMantenimiento que defina las operaciones Create, Update y Delete Crear una clase Producto que implemente IMantenimiento, para implementar Create, Update y Delete reuse la clase del paso 1 (use Adapter)

El patrn Template Method


Definicin


Whenever you write a parent class where you leave one or more of the methods to be implemented by derived classes, you are in essence using the Template pattern. The Template pattern formalizes the idea of defining an algorithm in a class but leaving some of the details to be implemented in subclasses.
A template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior.

El patrn Template Method


Modelo
Defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm. Implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.

implements the primitive operations ot carry out subclass-specific steps of the algorithm

El patrn Template Method


Ejemplo de Cdigo Abstract Class
Public MustInherit Class AccountsProcessor Protected m_Amount As Integer Public Sub Process(ByVal Account As String) Console.WriteLine(Account & " adjusted by " & m_Amount) End Sub Public MustOverride Sub SetAmount(ByVal Amount As Double) End Class

El patrn Template Method


Ejemplo de Cdigo Concrete Classes
Public Class DebitsProcessor Inherits AccountsProcessor Public Overrides Sub SetAmount(ByVal Amount As Double) m_Amount = Math.Round(Amount, 2) * 100 End Sub End Class Public Class CreditsProcessor Inherits AccountsProcessor Public Overrides Sub SetAmount(ByVal Amount As Double) m_Amount = -1 * Math.Round(Amount, 2) * 100 End Sub End Class

El patrn Template Method


Ejemplo de Cdigo Client TEST
Dim objDebitsProcessor As New DebitsProcessor() Dim objCreditsProcessor As New CreditsProcessor() Console.WriteLine( _ "Increment the Training Expense account by $10.50...") objDebitsProcessor.SetAmount(10.5D) objDebitsProcessor.Process("Training Expense") Console.WriteLine( _ "Decrement the Accounts Payable by $10.50...") objCreditsProcessor.SetAmount(10.5D) objCreditsProcessor.Process("Accounts Payable") MessageBox.Show("Click OK to end")

El patrn Template Method


Implementacin en el .Net Framework


In ASP.NET custom controls, you don't have to write any code to handle the functionality that's common to all controls, like loading and saving ViewState at the right time, allowing PostBack events to be handled, and making sure the control lifecycle events are raised in the correct order.
The main algorithm for how a control should be loaded, rendered, and unloaded is contained in the control base class (like Control or WebControl) The specifics of your particular control are handled at well-defined wellplaces in the control algorithm (the CreateChildControls or Render methods).

El patrn Template Method


Implementacin en el .Net Framework

Patrn Template Method

El patrn Template Method


Ejercicio


Consider an application framework that provides Application and Document classes. The Application class is responsible for opening existing documents stored in an external format, such as a file. A Document object represents the information in a document once it's read from the file. Applications built with the framework can subclass Application and Document to suit specific needs. For example, a drawing application defines DrawApplication and DrawDocument subclasses; a spreadsheet application defines SpreadsheetApplication and SpreadsheetDocument subclasses. The abstract Application class defines the algorithm for opening and reading a document in its OpenDocument operation. OpenDocument defines each step for opening a document. It checks if the document can be opened, creates the application-specific applicationDocument object, adds it to its set of documents, and reads the Document from a file.

El patrn Iterator
Definicin


The Iterator pattern allows you to move through a list or collection of data using a standard interface without having to know the details of the internal representations of that data.
In addition, you can also define special iterators that perform some special processing and return only specified elements of the data collection.

El patrn Iterator
Modelo
Defines an interface for accessing and traversing elements

Defines an interface for creating an Iterator object

Implements the Iterator creation interface to return an instance of the proper ConcreteIterator

Implements the Iterator interface. Keeps track of the current position in the traversal of the aggregate.

El patrn Iterator
Ejemplo de Cdigo Aggregate
abstract class Aggregate { // Methods public abstract Iterator CreateIterator(); }

El patrn Iterator
Ejemplo de Cdigo Concrete Aggregate
class ConcreteAggregate : Aggregate { private ArrayList items = new ArrayList(); public override Iterator CreateIterator() { return new ConcreteIterator( this ); } public int Count { get{ return items.Count; } } public object this[ int index ] { get{ return items[ index ]; } set{ items.Insert( index, value ); } } }

El patrn Iterator
Ejemplo de Cdigo Iterator

abstract class Iterator { // Methods public abstract object First(); public abstract object Next(); public abstract bool IsDone(); public abstract object CurrentItem(); }

El patrn Iterator
Ejemplo de Cdigo Concrete Iterator
class ConcreteIterator : Iterator { private ConcreteAggregate aggregate; private int current = 0; public ConcreteIterator( ConcreteAggregate aggregate ) this.aggregate = aggregate; } override public object First() return aggregate[ 0 ]; } { {

override public object Next() { if( current < aggregate.Count-1 ) return aggregate[ ++current ]; else return null; } override public object CurrentItem() return aggregate[ current ]; } {

override public bool IsDone() { return current >= aggregate.Count ? true : false ; } }

El patrn Iterator
Ejemplo de Cdigo Client
public class Client { public static void Main(string[] args) { ConcreteAggregate a = new ConcreteAggregate(); a[0] = "Item A"; a[1] = "Item B"; a[2] = "Item C"; a[3] = "Item D"; ConcreteIterator i = new ConcreteIterator(a); object item = i.First(); while( item != null ) { Console.WriteLine( item ); item = i.Next(); } } }

El patrn Iterator
Implementacin en el .NET Framework Many of the .NET System.Collections assembly classes support all the functionality of the Iterator pattern through a call to GetEnumerator(), which returns a concrete iterator, the IEnumerator interface.
string[] cities = {"New York","Paris","London"}; foreach(string city in cities) { Console.WriteLine(city); }

In fact, you can use any custom data collection in the foreach loop, as long as that collection type implements a GetEnumerator method that returns an IEnumerator interface.

El patrn Iterator
Implementacin en el .NET Framework You can return an IEnumerator interface implementing the IEnumerable interface:
Public Interface IEnumerable Public Overridable Function GetEnumerator() As System.Collections.IEnumerator End Interface Public Interface IEnumerator Sub Reset() Function MoveNext() As Boolean ReadOnly Property Current() As Object End Interface

El patrn Iterator
Implementacin en el .NET Framework Often, the class that is used to iterate over a collection by implementing IEnumerable is provided as a nested class of the collection type to be iterated. This iterator type maintains the state of the iteration. A nested class is often better as an enumerator because it has access to all the private members of its containing class.

Patrn Iterator

El patrn Iterator
Ejercicio


Utilice el patron Iterator para almacenar una lista de objetos Empleado en una coleccin En un ListBox listar los objetos, debe mostrarse el nombre de cada empleado Al hacer clic sobre el nombre del empleado debe aparecer los datos del empleado.

El patrn Composite
Definicin


A composite is a collection of objects, any one of which may be either a composite or just a primitive object. In tree nomenclature, some objects may be nodes with additional branches and some may be leaves
You can use the Composite to build part-whole parthierarchies or to construct data representations of trees.

El patrn Composite
Modelo

- Declares the interface for objects in the composition. - Implements default behavior for the interface common to all classes, as appropriate. - Declares an interface for accessing and managing its child components.

Manipulates objects in the composition through the Component interface Defines behavior for components having children. Stores child components. implements child-related operations in the Component interface.

Represents leaf objects in the composition. A leaf has no children. defines behavior for primitive objects in the composition.

El patrn Composite
Ejemplo de Cdigo Component
abstract class DrawingElement { // Fields protected string name; // Constructors public DrawingElement( string name ) { this.name = name; } // Methods abstract public void Add( DrawingElement d ); abstract public void Remove( DrawingElement d ); abstract public void Display( int indent ); }

El patrn Composite
Ejemplo de Cdigo Leaf
class PrimitiveElement : DrawingElement { public PrimitiveElement( string name ) : base( name ) {} public override void Add( DrawingElement c ) { Console.WriteLine("Cannot Add"); } public override void Remove( DrawingElement c ) { Console.WriteLine("Cannot Remove"); } public override void Display( int indent ) { Console.WriteLine( new String( '-', indent ) + " draw a {0}", name ); } }

El patrn Composite
Ejemplo de Cdigo Composite
class CompositeElement : DrawingElement { private ArrayList elements = new ArrayList(); public CompositeElement( string name ) : base( name ) {} public override void Add( DrawingElement d ) { elements.Add( d ); } public override void Remove( DrawingElement d ) { elements.Remove( d ); } public override void Display( int indent ) { Console.WriteLine( new String( '-', indent ) + "+ " + name ); foreach( DrawingElement c in elements ) c.Display( indent + 2 ); } }

El patrn Composite
Ejemplo de Cdigo Test Client
CompositeElement root = new CompositeElement( "Picture" ); root.Add( new PrimitiveElement( "Red Line" )); root.Add( new PrimitiveElement( "Blue Circle" )); root.Add( new PrimitiveElement( "Green Box" )); CompositeElement comp = new CompositeElement( "Two Circles" ); comp.Add( new PrimitiveElement( "Black Circle" ) ); comp.Add( new PrimitiveElement( "White Circle" ) ); root.Add( comp ); // Add and remove a PrimitiveElement PrimitiveElement l = new PrimitiveElement( "Yellow Line" ); root.Add( l ); root.Remove( l ); // Recursively display nodes root.Display( 1 );

El patrn Composite
Implementacin en el .NET Framework


Think about an ASP.NET control. A control may be a simple single item like a Literal, or it could be composed of a complex collection of child controls, like a DataGrid is. Regardless, calling the Render method on either of these controls should still perform the same intuitive function.

El patrn Composite
Implementacin en el .NET Framework

The Component is the ASP.NET System.Web.UI.Control.


Control represents the Component base class. It has operations for dealing with children (such as the child Controls property) as well as standard operations and properties like Render and Visible. Each object, whether a primitive object (like Literal) or a composite of several objects (like DataGrid), inherits from this base class.

El patrn Composite
Implementacin en el .NET Framework

Because the domain of controls is so diverse, there are several intermediate derived classes like WebControl and BaseDataList that serve as base classes for other controls. Though these classes expose additional properties and methods, they still retain the child management functions and core operations inherited from Control.
Regardless of whether a control is a Literal or a DataGrid, the use of Composite means you can just call Render and everything will sort itself out.

Patrn Composite

El patrn State
Definicin


The State pattern is used when you want to have an object represent the state of your application and switch application states by switching objects.
For example, you could have an enclosing class switch between a number of related contained classes and pass method calls on to the current contained class. Design Patterns suggests that the State pattern switches between internal classes in such a way that the enclosing object appears to change its class.

El patrn State
Definicin


Many programmers have had the experience of creating a class that performs slightly different computations or displays different information based on the arguments passed into the class. This frequently leads to some types of select case or if-else statements inside the class that ifdetermine which behavior to carry out. It is this inelegance that the State pattern seeks to replace.

El patrn State
Modelo

Defines an interface for encapsulating the behavior associated with a particular state of the Context.

- Defines the interface of interest to clients - Maintains an instance of a ConcreteState subclass that defines the current state.

Each subclass implements a behavior associated with a state of Context

El patrn State
Ejemplo de Cdigo State
MustInherit Class State Protected Sub New() End Sub MustOverride Sub GoToAlberta(ByRef tm As TravelManager) MustOverride Sub GoToWashington(ByRef tm As TravelManager) MustOverride Sub GoToHawaii(ByRef tm As TravelManager) Protected Sub ChangeState(ByRef tm As TravelManager, _ ByRef s As State) tm.ChangeState(s) End Sub End Class

El patrn State
Ejemplo de Cdigo Concrete State
Public Class Alberta Inherits State Private Shared m_State = New Alberta() Private Sub New() End Sub Public Shared Function Instance() As State Console.WriteLine("Welcome to Alberta!") Return m_State End Function Public Overrides Sub GoToAlberta(ByRef tm As TravelManager) Console.WriteLine("You are already in Alberta.") End Sub Public Overrides Sub GoToWashington(ByRef tm As TravelManager) Console.WriteLine("Enjoy the drive to America.") ChangeState(tm, Washington.Instance) End Sub Public Overrides Sub GoToHawaii(ByRef tm As TravelManager) Console.WriteLine("Enjoy your flight to Hawaii.") ChangeState(tm, Hawaii.Instance) End Sub End Class

El patrn State
Ejemplo de Cdigo Concrete State
Public Class Hawaii Inherits State Private Shared m_State = New Hawaii() Private Sub New() End Sub Public Shared Function Instance() As State Console.WriteLine("Welcome to Hawaii!") Return m_State End Function Public Overrides Sub GoToAlberta(ByRef tm As TravelManager) Console.WriteLine("Enjoy your flight to Canada.") ChangeState(tm, Alberta.Instance) End Sub Public Overrides Sub GoToWashington(ByRef tm As TravelManager) Console.WriteLine("Enjoy your flight to Washington.") ChangeState(tm, Washington.Instance) End Sub Public Overrides Sub GoToHawaii(ByRef tm As TravelManager) Console.WriteLine("You are already in Hawaii.") End Sub End Class

El patrn State
Ejemplo de Cdigo Concrete State
Public Class Washington Inherits State Private Shared m_State = New Washington() Private Sub New() End Sub Public Shared Function Instance() As State Console.WriteLine("Welcome to Washington!") Return m_State End Function Public Overrides Sub GoToAlberta(ByRef tm As TravelManager) Console.WriteLine("Enjoy the drive to Canada.") ChangeState(tm, Alberta.Instance) End Sub Public Overrides Sub GoToWashington(ByRef tm As TravelManager) Console.WriteLine("You are already in Washington.") End Sub Public Overrides Sub GoToHawaii(ByRef tm As TravelManager) Console.WriteLine("Enjoy your flight to Hawaii.") ChangeState(tm, Hawaii.Instance) End Sub End Class

El patrn State
Ejemplo de Cdigo Context
Class TravelManager Private m_State As State Public Sub New() Console.WriteLine("Travel Manager starting...") m_State = Washington.Instance End Sub Public Sub ChangeState(ByVal s As State) m_State = s End Sub Public Sub GoToAlberta() m_State.GoToAlberta(Me) End Sub Public Sub GoToWashington() m_State.GoToWashington(Me) End Sub Public Sub GoToHawaii() m_State.GoToHawaii(Me) End Sub End Class

El patrn State
Ejemplo de Cdigo TEST CLIENT
Dim objTravelManager As New TravelManager() With objTravelManager Console.WriteLine("Requesting a trip to Alberta....") .GoToAlberta() Console.WriteLine("Now requesting a trip to Hawaii....") .GoToHawaii() Console.WriteLine("Now requesting a trip to Washington....") .GoToWashington() Console.WriteLine( _ "Now let's try requesting the Washington trip again....") .GoToWashington() End With

Patrn State

El patrn Decorator
Definicin


The Decorator pattern provides us with a way to modify the behavior of individual objects without having to create a new derived class.
Suppose we have a program that uses eight objects, but three of them need an additional feature. You could create a derived class for each of these objects However, if each of these three objects requires different features, this would mean creating three derived classes. Further, if one of the classes has features of both of the other classes, you begin to create complexity that is both confusing and unnecessary.

El patrn Decorator
Definicin


Suppose we wanted to draw a special border around some of the buttons in a toolbar. If we created a new derived button class, this means that all of the buttons in this new class would always have this same new border We create a Decorator class that decorates the buttons. Then we derive any number of specific Decorators from the main Decorator class, each of which performs a specific kind of decoration. In order to decorate a button, the Decorator has to be an object derived from the visual environment so it can receive paint method calls and forward calls to other useful graphic methods to the object that it is decorating. The decorator is a graphical object, but it contains the object it is decorating. It may intercept some graphical method calls, perform some additional computation, and pass them on to the underlying object it is decorating

El patrn Decorator
Modelo
Defines the interface for objects that can have responsibilities added to them dynamically.

Maintains a reference to a Component object and defines an interface that conforms to Component's interface.

Defines an object to which additional responsibilities can be attached.

Adds responsibilities to the component

El patrn Decorator
Ejemplo de Cdigo Component
abstract class LibraryItem { // Fields private int numCopies; // Properties public int NumCopies { get{ return numCopies; } set{ numCopies = value; } } // Methods public abstract void Display(); }

El patrn Decorator
Ejemplo de Cdigo Concrete Component
class Book : LibraryItem { // Fields private string author; private string title; // Constructors public Book(string author,string title,int numCopies) { this.author = author; this.title = title; this.NumCopies = numCopies; } // Methods public override void { Console.WriteLine( Console.WriteLine( Console.WriteLine( Console.WriteLine( } }

Display() "\nBook ------ " ); " Author: {0}", author ); " Title: {0}", title ); " # Copies: {0}", NumCopies );

El patrn Decorator
Ejemplo de Cdigo Concrete Component
class Video : LibraryItem { private string director; private string title; private int playTime; public Video( string director, string title, int numCopies, int playTime ) { this.director = director; this.title = title; this.NumCopies = numCopies; this.playTime = playTime; } public override void { Console.WriteLine( Console.WriteLine( Console.WriteLine( Console.WriteLine( Console.WriteLine( } } Display() "\nVideo ----- " ); " Director: {0}", director ); " Title: {0}", title ); " # Copies: {0}", NumCopies ); " Playtime: {0}", playTime );

El patrn Decorator
Ejemplo de Cdigo Decorator
abstract class Decorator : LibraryItem { // Fields protected LibraryItem libraryItem; // Constructors public Decorator ( LibraryItem libraryItem ) { this.libraryItem = libraryItem; } // Methods public override void Display() { libraryItem.Display(); } }

El patrn Decorator
Ejemplo de Cdigo Concrete Decorator
class Borrowable : Decorator { protected ArrayList borrowers = new ArrayList(); public Borrowable( LibraryItem libraryItem ) : base( libraryItem ) {} public void BorrowItem( string name ) { borrowers.Add( name ); libraryItem.NumCopies--; } public void ReturnItem( string name ) { borrowers.Remove( name ); libraryItem.NumCopies++; } public override void Display() { base.Display(); foreach( string borrower in borrowers ) Console.WriteLine( " borrower: {0}", borrower ); } }

El patrn Decorator
Ejemplo de Cdigo TEST APP
public class DecoratorApp { public static void Main( string[] args ) { // Create book and video and display Book book = new Book( "Schnell", "My Home", 10 ); Video video = new Video( "Spielberg", "Schindler's list", 23, 60 ); book.Display(); video.Display(); // Make video borrowable, then borrow and display Console.WriteLine( "\nVideo made borrowable:" ); Borrowable borrowvideo = new Borrowable( video ); borrowvideo.BorrowItem( "Cindy Lopez" ); borrowvideo.BorrowItem( "Samuel King" ); borrowvideo.Display(); } }

El patrn Decorator
Implementacin en el .NET Framework Any useful executable program involves either reading input, writing output, or both. Regardless of the source of the data being read or written, it can be treated abstractly as a sequence of bytes. .NET uses the System.IO.Stream class to represent this abstraction. Whether the data involves characters in a text file, TCP/IP network traffic, or something else entirely, chances are you will have access to it via a Stream. Since the class for working with file data (FileStream) and the class for working with network traffic (NetworkStream) both inherit from Stream, you can easily write code that processes the data independent of its origins.

El patrn Decorator
Implementacin en el .NET Framework Here's a method for printing out some bytes from a Stream to the console:
public static void PrintBytes(Stream s) { int b; while((b = fs.ReadByte()) >= 0) { Console.Write(b + " "); } }

El patrn Decorator
Implementacin en el .NET Framework The Framework includes the BufferedStream class to read a chuck of bytes. The constructor for BufferedStream takes as the parameter whatever stream you would like buffered access to. BufferedStream overrides the main methods of Stream, such as Read and Write, to provide more functionality. Since it is still a child class of Stream, you can use it the same as any other Stream . Similarly, you can use System.Security.Cryptography.CryptoStream to encrypt and decrypt Streams on the fly, without the rest of the application needing to know anything more than the fact that it is a Stream.

El patrn Decorator
Implementacin en el .NET Framework The code shows several calls to my printing method using different Streams.
MemoryStream ms = new MemoryStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8}); PrintBytes(ms); BufferedStream buff = new BufferedStream(ms); PrintBytes(buff); buff.Close(); FileStream fs = new FileStream("../../decorator.txt", FileMode.Open); PrintBytes(fs); fs.Close();

El patrn Decorator
Implementacin en el .NET Framework
This ability to dynamically attach new functionality to objects transparently using composition is an example of the Decorator pattern. Given any instance of Stream, you can add the capability for buffered access by wrapping it in a BufferedStream, without changing the interface to the data

Patrn Decorator

El patrn Decorator
Ejercicio

1. When someone enters an incorrect value in a cell of a grid, you might want to change the color of the row to indicate the problem. Suggest how you could use a Decorator. 2. A mutual fund is a collection of stocks. Each one consists of an array or Collection of prices over time. Can you see how a Decorator can be used to produce a report of stock performance for each stock and for the whole fund?

El patrn Facade
Definicin


The Faade pattern is used to wrap a set of complex classes into a simpler enclosing interface. As your programs evolve and develop, they grow in complexity. As we start using design patterns, these patterns sometimes generate so many classes that it is difficult to understand the programs flow.

El patrn Facade
Definicin


Furthermore, there may be a number of complicated subsystems, each of which has its own complex interface.
The Faade pattern allows you to simplify this complexity by providing a simplified interface to these subsystems. This simplification may in some cases reduce the flexibility of the underlying classes, but it usually provides all the function needed for all but the most sophisticated users. These users can still, access the underlying classes and methods.

El patrn Facade
Modelo

- Knows which subsystem classes are responsible for a request. -Delegates client requests to appropriate subsystem objects.

- Implement subsystem functionality. - Handle work assigned by the Facade object. - Have no knowledge of the facade and keep no reference to it.

El patrn Facade
Ejemplo de Cdigo Subsystems Class A, ClassB y Class C
class Bank { public bool SufficientSavings( Customer c ) { Console.WriteLine("Check bank for {0}", c.Name ); return true; } } class Credit { public bool GoodCredit( int amount, Customer c ) { Console.WriteLine( "Check credit for {0}", c.Name ); return true; } } class Loan { public bool GoodLoan( Customer c ) { Console.WriteLine( "Check loan for {0}", c.Name ); return true; } }

El patrn Facade
Ejemplo de Cdigo <Business Entity>
class Customer { // Fields private string name; // Constructors public Customer( string name ) { this.name = name; } // Properties public string Name { get{ return name; } } }

El patrn Facade
Ejemplo de Cdigo Facade
class MortgageApplication { int amount; private Bank bank = new Bank(); private Loan loan = new Loan(); private Credit credit = new Credit(); public MortgageApplication( int amount ) { this.amount = amount; } public bool IsEligible( Customer c ) { if( !bank.SufficientSavings( c ) ) return false; if( !loan.GoodLoan( c ) ) return false; if( !credit.GoodCredit( amount, c )) return false; return true; } }

El patrn Facade
Comparing the Facade Pattern with the Adapter Pattern
Facade Are there preexisting classes? Yes Is there an interface we must design No to? Does an object need to behave No polymorphically? Is a simpler interface needed? Yes Adapter Yes Yes Probably No

Patrn Facade

El patrn Facade
Ejercicio

1. Suppose you had written a program with a File|Open menu, a text field, and some buttons controlling font (bold and italic). Now suppose that you need to have this program run from a line command with arguments. Suggest how to use a Faade pattern.

El patrn Proxy
Definicin


The Proxy pattern is used when you need to represent an object that is complex or time consuming to create, by a simpler one.
If creating an object is expensive in time or computer resources, Proxy allows you to postpone this creation until you need the actual object. A Proxy usually has the same methods as the object it represents, and once the object is loaded, it passes on the method calls from the Proxy to the actual object.

El patrn Proxy
Definicin


There are several cases where a Proxy can be useful:


1. 2.

3.

4.

An object, such as a large image, takes a long time to load. The results of a computation take a long time to complete, and you need to display intermediate results while the computation continues. The object is on a remote machine, and loading it over the network may be slow, especially during peak network load periods. The object has limited access rights, and the proxy can validate the access permissions for that user.methods.

El patrn Proxy
Definicin


You see more proxy- like behavior in .NET because proxyit is crafted for network and Internet use. For example, the ADO.Net database connection classes are all effectively proxies.

El patrn Proxy
Modelo
- Defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.

- Maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject and Subject interfaces are the same. - Provides an interface identical to Subject's so that a proxy can be substituted for for the real subject. - Controls access to the real subject and may be responsible for creating and deleting it.

Defines the real object that the proxy represents.

El patrn Proxy
Ejemplo de Cdigo Subject
public interface IMath { // Methods double Add( double x, double Sub( double x, double Mul( double x, double Div( double x, }

double double double double

y y y y

); ); ); );

El patrn Proxy
Ejemplo de Cdigo Real Subject
class Math : MarshalByRefObject, IMath { // Methods public double Add( double x, double y public double Sub( double x, double y public double Mul( double x, double y public double Div( double x, double y }

){ ){ ){ ){

return return return return

x x x x

+ * /

y; y; y; y;

} } } }

El patrn Proxy
Ejemplo de Cdigo Remote Proxy Object
class MathProxy : IMath { Math math; public MathProxy() { AppDomain ad = System.AppDomain.CreateDomain( "MathDomain",null, null ); ObjectHandle o = ad.CreateInstance("Proxy_RealWorld", "Math", false, System.Reflection.BindingFlags.CreateInstance, null, null, null,null,null ); math = (Math) o.Unwrap(); } 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); } }

El patrn Proxy
Ejemplo de Cdigo TEST APP
public class ProxyApp { public static void Main( string[] args ) { // Create math proxy MathProxy p = new MathProxy(); // Do the math Console.WriteLine( Console.WriteLine( Console.WriteLine( Console.WriteLine( } }

"4 "4 "4 "4

+ * /

2 2 2 2

= = = =

{0}", {0}", {0}", {0}",

p.Add( p.Sub( p.Mul( p.Div(

4, 4, 4, 4,

2 2 2 2

) ) ) )

); ); ); );

Patrn Proxy

El patrn Proxy
Ejercicio


You have designed a server that connects to a database. If several clients connect to your server at once, how might Proxies be of help?

El patrn Bridge
Definicin


The Bridge pattern is designed to separate a classs interface from its implementation so you can vary or replace the implementation without changing the client code.

El patrn Bridge
Modelo

- Defines the abstraction's interface. maintains a reference to an object of type Implementor.

- Defines the interface for implementation classes. This interface doesn't have to correspond exactly to Abstraction's interface; in fact the two interfaces can be quite different. Typically the Implementation interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.

- Extends the interface defined by Abstraction.

- Implements the Implementor interface and defines its concrete implementation.

El patrn Bridge
Ejemplo de Cdigo Abstraction
class BusinessObject { private DataObject dataObject; protected string group; public BusinessObject( string group ) { this.group = group; } public DataObject DataObject { set{ dataObject = value; } get{ return dataObject; } } virtual public void Next() { dataObject.NextRecord(); } virtual public void Prior() { dataObject.PriorRecord(); } virtual public void New( string name ) { dataObject.NewRecord( name ); } virtual public void Delete( string name ) { dataObject.DeleteRecord( name ); } virtual public void Show() { dataObject.ShowRecord(); } virtual public void ShowAll() { Console.WriteLine( "Customer Group: {0}", group ); dataObject.ShowAllRecords(); } }

El patrn Bridge
Ejemplo de Cdigo Refined Abstraction
class CustomersBusinessObject : BusinessObject { // Constructors public CustomersBusinessObject( string group ) : base( group ){} // Methods override public void ShowAll() { // Add separator lines Console.WriteLine(); Console.WriteLine( "------------------------" ); base.ShowAll(); Console.WriteLine( "------------------------" ); } }

El patrn Bridge
Ejemplo de Cdigo Implementor
abstract class DataObject { // Methods abstract public void NextRecord(); abstract public void PriorRecord(); abstract public void NewRecord( string name ); abstract public void DeleteRecord( string name ); abstract public void ShowRecord(); abstract public void ShowAllRecords(); }

El patrn Bridge

(Concrete Implementor)

class CustomersDataObject : DataObject { private ArrayList customers = new ArrayList(); private int current = 0; public CustomersDataObject() { customers.Add( "Jim Jones" ); customers.Add( "Samual Jackson" ); customers.Add( "Allen Good" ); customers.Add( "Ann Stills" ); customers.Add( "Lisa Giolani" ); } public override void NextRecord() { if( current <= customers.Count - 1 ) current++; } public override void PriorRecord() { if( current > 0 ) current--; } public override void NewRecord( string name ) { customers.Add( name ); } public override void DeleteRecord( string name ) { customers.Remove( name ); } public override void ShowRecord() { Console.WriteLine( customers[ current ] ); } public override void ShowAllRecords() { foreach( string name in customers ) Console.WriteLine( " " + name ); } }

El patrn Bridge
Ejemplo de Cdigo TEST CLIENT
public class BusinessApp { public static void Main( string[] args ) { CustomersBusinessObject customers = new CustomersBusinessObject(" Chicago "); customers.DataObject = new CustomersDataObject(); customers.Show(); customers.Next(); customers.Show(); customers.Next(); customers.Show(); customers.New( "Henry Velasquez" ); customers.ShowAll(); } }

Patrn Bridge

El patrn Bridge
Ejercicio


In plotting a stocks performance, you usually display the price and priceearnings ratio over time, whereas in plotting a mutual fund, you usually show the price and the earnings per quarter. Suggest how you can use a Bridge to do both.

El patrn Strategy
Definicin


The Strategy pattern consists of a number of related algorithms encapsulated in a driver class called the Context. Your client program can select one of these differing algorithms, or in some cases, the Context might select the best one for you. The intent is to make these algorithms interchangeable and provide a way to choose the most appropriate one.

El patrn Strategy
Definicin


A program that requires a particular service or function and that has several ways of carrying out that function is a candidate for the Strategy pattern. Programs choose between these algorithms based on computational efficiency or user choice. There can be any number of strategies, more can be added, and any of them can be changed at any time.

El patrn Strategy
Definicin


There are a number of cases in programs where wed like to do the same thing in several different ways.
Save files in different formats. Compress files using different algorithms Capture video data using different compression schemes. Use different line-breaking strategies to display text data. linePlot the same data in different formats: line graph, bar chart, or pie chart.

El patrn Strategy
Modelo

Declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy

- Is configured with a ConcreteStrategy object - Maintains a reference to a Strategy object - May define an interface that lets Strategy access its data. implements the algorithm using the Strategy interface

El patrn Strategy
Ejemplo de Cdigo Strategy
abstract class SortStrategy { // Methods abstract public void Sort( ArrayList list ); }

El patrn Strategy
Ejemplo de Cdigo Concrete Strategy
class QuickSort : SortStrategy { public override void Sort(ArrayList list ) list.Sort(); // Default is Quicksort Console.WriteLine("QuickSorted list "); } } class ShellSort : SortStrategy { public override void Sort(ArrayList list ) //list.ShellSort(); Console.WriteLine("ShellSorted list "); } } {

class MergeSort : SortStrategy { public override void Sort( ArrayList list ) { //list.MergeSort(); Console.WriteLine("MergeSorted list "); } }

El patrn Strategy
Ejemplo de Cdigo Context
class SortedList { private ArrayList list = new ArrayList(); private SortStrategy sortstrategy; public void SetSortStrategy( SortStrategy sortstrategy ) this.sortstrategy = sortstrategy; } public void Sort() { sortstrategy.Sort( list ); } public void Add( string name ) { list.Add( name ); } public void Display() { foreach( string name in list ) Console.WriteLine( " " + name ); } } {

Patrn Strategy

El patrn Abstract Factory


Definicin


The Abstract Factory pattern is one level of abstraction higher than the factory pattern. You can use this pattern when you want to return one of several related classes of objects, each of which can return several different objects on request. In other words, the Abstract Factory is a factory object that returns one of several groups of classes. You might even decide which class to return from that group using a Simple Factory.

El patrn Abstract Factory


Definicin


Common thought experiment-style examples might experimentinclude automobile factories. You would expect a Toyota factory to work exclusively with Toyota parts and a Ford factory to use Ford parts. You can consider each auto factory as an Abstract Factory and the parts the groups of related classes.

El patrn Abstract Factory


Modelo
Declares an interface for a type of product object

declares an interface for operations that create abstract products

implements the operations to create concrete product objects

- Defines a product object to be created by the corresponding concrete factory - Implements the AbstractProduct interface

El patrn Abstract Factory


Ejemplo de Cdigo Abstract Factory
abstract class ContinentFactory { // Methods abstract public Herbivore CreateHerbivore(); abstract public Carnivore CreateCarnivore(); }

El patrn Abstract Factory


Ejemplo de Cdigo Concrete Factory
class AfricaFactory : ContinentFactory { override public Herbivore CreateHerbivore() return new Wildebeest(); } override public Carnivore CreateCarnivore() return new Lion(); } } class AmericaFactory : ContinentFactory { override public Herbivore CreateHerbivore() return new Bison(); } override public Carnivore CreateCarnivore() return new Wolf(); } } {

El patrn Abstract Factory


Ejemplo de Cdigo Abstract Product
abstract class Herbivore { } abstract class Carnivore { // Methods abstract public void Eat( Herbivore h ); }

El patrn Abstract Factory


Ejemplo de Cdigo Product
class Wildebeest : Herbivore { } class Lion : Carnivore { override public void Eat( Herbivore h ) { Console.WriteLine( this + " eats " + h ); } } class Bison : Herbivore { } class Wolf : Carnivore { override public void Eat( Herbivore h ) { Console.WriteLine( this + " eats " + h ); } }

El patrn Abstract Factory


Ejemplo de Cdigo Client
class AnimalWorld { // Fields private Herbivore herbivore; private Carnivore carnivore; // Constructors public AnimalWorld( ContinentFactory factory ) { carnivore = factory.CreateCarnivore(); herbivore = factory.CreateHerbivore(); } // Methods public void RunFoodChain() { carnivore.Eat( herbivore ); } }

El patrn Abstract Factory


Ejemplo de Cdigo TEST APP
class GameApp { public static void Main( string[] args ) { // Create and run the Africa animal world ContinentFactory africa = new AfricaFactory(); AnimalWorld world = new AnimalWorld( africa ); world.RunFoodChain(); // Create and run the America animal world ContinentFactory america = new AmericaFactory(); world = new AnimalWorld( america ); world.RunFoodChain(); } }

Patrn Abstract Factory

El patrn Abstract Factory


Ejercicio


If you are writing a program to track investments, such as stocks, bonds, metal futures, derivatives, and the like, how might you use an Abstract Factory?

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0


The idea behind this version of the DAAB is to provide an easy support to make the data access independent of the ADO.NET provider In ADO.NET some interfaces are provided to create the ADO.NET providers. Those interfaces are: IDbConnection, IDbTransaction, IDbCommand, IDataParameter, IDataReader, IDataRecord, etc.

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0


Every ADO.NET provider must implement those interfaces on its implementation classes, so there's an open door to write code that doesn't knows which ADO.NET provider it is using if the code is using interfaces instead of concrete classes. The ADO.NET interfaces define a common base of functionality supported by almost any database

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0
Dim conn As IDbConnection = GetConnection() conn.Open() Dim cmd As IDbCommand = conn.CreateCommand cmd.CommandText = "Select ProductName from Products" Dim reader As IDataReader = cmd.ExecuteReader While (reader.Read) ListBox1.Items.Add(reader("ProductName").ToString) End While reader.Close() conn.Close() Private Function GetConnection() As IDbConnection Dim strCon As String = _ "Data Source=(local);Initial Catalog=Northwind;" Return New SqlClient.SqlConnection(strCon) End Function

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0


The DAAB 2.0 allows very easy access to the Sql Server ADO.NET driver using single line methods for example ExecuteDataset, ExecuteReader, etc. Every method was implemented as a static method of a single class named SqlHelper and uses the SqlServer ADO.NET provider only. The only way to extend this class in order to use a different ADO.NET driver is rewriting the code whole. In DAAB 3.0 the main helper class is named AdoHelper and it defines the same methods that were defined on SqlHelper, but using the ADO.NET interfaces instead using the SqlServer implementations

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0


The AdoHelper is an abstract class, so it cant be instantiated, this class can only be used by derived classes. For example, the classes named SqlServer, Odbc, OleDb, and Oracle extend AdoHelper The AdoHelper class defines some static methods that can be used to create AdoHelper derived classes, using the Abstract Factory design pattern. The method used to create pattern. an instance of the AdoHelper derived class is CreateHelper

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0
AbstractProduct AbstractProduct

ConcreteProduct

ConcreteProduct

El patrn Abstract Factory


AbstractFactory

ConcreteFactory ConcreteFactory ConcreteFactory

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0
Public Function GetAdoHelper() As AdoHelper Dim [assembly] As String = Nothing Dim type As String = Nothing Select Case lstData.SelectedItem.ToString() Case "SqlServer" [assembly] = ConfigurationSettings.AppSettings("SqlServerHelperAssembly") type = ConfigurationSettings.AppSettings("SqlServerHelperType") Case "OleDb" [assembly] = ConfigurationSettings.AppSettings("OleDbHelperAssembly") type = ConfigurationSettings.AppSettings("OleDbHelperType") Case "Odbc" [assembly] = ConfigurationSettings.AppSettings("OdbcHelperAssembly") type = ConfigurationSettings.AppSettings("OdbcHelperType") End Select Return AdoHelper.CreateHelper([assembly], type) End Function 'GetAdoHelper <appSettings> <add key="SqlServerConnectionString" value="Data Source=localhost;Initial catalog=DAABAF;user id=sa" /> <add key="SqlServerHelperAssembly" value="GotDotNet.ApplicationBlocks.Data"></add> <add key="SqlServerHelperType" value="GotDotNet.ApplicationBlocks.Data.SqlServer"></add>

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0
Public Overloads Shared Function CreateHelper( _ ByVal providerAssembly As String, _ ByVal providerType As String) As AdoHelper Dim [assembly] As [assembly] = [assembly].Load(providerAssembly) Dim provider As Object = [assembly].CreateInstance(providerType) If TypeOf provider Is AdoHelper Then Return DirectCast(provider, AdoHelper) Else Throw New InvalidOperationException(error") End If End Function

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0
Public Function GetConnectionString() As String Dim connectionString As String = Nothing Select Case lstData.SelectedItem.ToString() Case "SqlServer" connectionString = _ ConfigurationSettings.AppSettings("SqlServerConnectionString") Case "OleDb" connectionString = _ ConfigurationSettings.AppSettings("OleDbConnectionString") Case "Odbc" connectionString = _ ConfigurationSettings.AppSettings("OdbcConnectionString") End Select Return connectionString End Function 'GetConnectionString

El patrn Abstract Factory


Caso de Estudio : DAAB 3.0
Dim helper As AdoHelper = GetAdoHelper() Dim cs As String = GetConnectionString() Dim ds As New DataSet helper.FillDataset(cs, CommandType.Text, _ "Select * from Customer", ds, New String() {"Customers"}) customerGrid.DataSource = ds customerGrid.DataMember = "Customers" Dim helper As AdoHelper = GetAdoHelper() Dim cs As String = GetConnectionString() helper.ExecuteNonQuery(cs, CommandType.Text, strSQLSentence)

Вам также может понравиться