In this article we are going to discuss the Proxy design pattern. It is one
among the 23 design patterns by Gof. As usual we can start with the Challenge
and Solution style.
You are working on automating Excel COM objects. The business logic has to think
too much about instantiating COM, doing ground works before calling the actual
The same code could get replaced by DCOM tomorrow. So the Excel access code is
spread throughout your application. How to do a better design?
"Provide a surrogate or placeholder for another object to control access to it."
We can solve the above problem by using a Proxy pattern. As the definition says,
we will have to create a placeholder or wrapper around the original object to
control access to it. In this way we can make the following advantages:
- Talk to COM or DCOM Excel object by changing configuration in one place
- Give application a simple interface to talk with Excel COM/DCOM
- Feel application think like it is talking to a local object
Following is the application with data:
Following is the old code where application is forced to think too much about
the Excel COM object and method of assigning values to the cells.
Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
headers going cell by cell.
1] = "Name";
oSheet.Cells[1, 2] = "Address";
oSheet.Cells[1, 3] = "Salary";
as bold, vertical alignment = center.
i = 2;
employee in _list)
string values =
values = employee.Name;
values = employee.Address;
values = employee.Salary.ToString();
+ i.ToString(), "C" + i.ToString()).Value =
oXL.UserControl = true;
The problem with above code is too much Excel logic is mixed with the
application logic. Now we can see the new code with proxy pattern implemented.
New Code with Proxy Pattern
= new ExcelProxy();
The code is only 2 lines and the Excel COM object creation, cell value assigning
etc are taken care by the ExcelProxy class.
On executing the application we can see the results inside Microsoft Excel.
Other Examples of Proxy Pattern
We can have many real world examples which implement the Proxy pattern. When we
add a WCF reference a Proxy is created. This class takes care of the connection
details, serialization etc.
In this article we have seen the usage of Proxy design pattern along with an
example. The source code attached contains the example we have discussed.