# Pattern of the Week: Proxy

This is the sixth in a series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Structural

This week’s pattern is called the Proxy pattern. This pattern is primarily used to add security or to implement caching for objects. For my example, I’ll be adding security to this class:

public class SomeService : ISomeService
{
public List<string> GetStrings()
{
return new List<string>
{
"String1",
"String2",
"String3"
};
}
}


This is a pretty simple class, which implements the following interface:

public interface ISomeService
{
List<string> GetStrings();
}


Now, suppose I want to make sure that not everyone has access to the GetStrings method. Well, I could modify the GetStrings method itself, and add some complex code to check a user’s permissions, or I could implement a Proxy to do that for me. The main benefit to using this approach is that I don’t overly complicate GetStrings, and I can separate these two concerns (permissions and data access). Here’s my Proxy class:

public class SomeServiceProxy : ISomeService
{

public SomeServiceProxy()
{
_someService = new SomeService();
}

public List<string> GetStrings()
{
ValidateAccess("GetStrings");

return _someService.GetStrings();
}

private void ValidateAccess(string methodName)
{
// Here, we could call some other class to get whether
// We could throw an exception if they dont have access.