Proxy Design Pattern
The Gang Of Four definition of this design pattern is "Provides a surrogate or placeholder for another object to control access to it". In the example below we use the pattern to enable caching on an ASP.net page. This code uses the Factory design pattern as well.
A VB Example of the Proxy Design Pattern
Dim productsProvider As IProducts
Dim cachingEnabled As Boolean = CType(System.Configuration.ConfigurationManager.AppSettings("caching"), Boolean)
productsProvider = ProductsFactory.getProductsProvider(cachingEnabled)
Me.ProductsGrid.DataSource = productsProvider.getProducts()
Me.ProductsGrid.DataBind()
Public Interface IProducts
Function getProducts() As String
End Interface
Public Class ProductsFactory
Public Shared Function getProductsProvider(ByVal UseCaching As Boolean) As IProducts
If UseCaching Then
Return New ProxyProducts
Else
Return New Products
End If
End Function
End Class
Public Class ProxyProducts
Implements IProducts Public Function getProducts() As String Implements IProducts.getProducts
End Function
End Class
Public Class Products
Implements IProducts
Public Function getProducts() As String Implements IProducts.getProducts
End Function
End Class
UML
This pattern is implemented to do memory management. Suppose in application it is required to initialize a class which contains a lot of properties and methods. If busness logic fails here, then loading this heavy class in the memory will be useless. Eg.
if (driver.Age <= 16)
return "Young driver";
else
{
realCar = new Car();
return realCar.MoveCar();
}
public class Car : ICar
{
}
Here the Car
class will only be initiallised if the age is greater than 16 else it will not be initiallized.