1

from my understanding i implement the proxy pattern when i hold a reference to another type as a member in my Proxy class. i also need to provides an interface, identical to the subject type, and Controls access to the real object.

so, if my code was to look like this, when the List member is the subject type, would i have been implementing the proxy pattern correctly?

public class ListUsers
{
    public List<User> UserList { get; set; }

    .
    .
    // Ctor and other methods that dont expose the "List<Users>" properties..
    .
    .

    public void Add(User i_User)
    {
        // added logic and control.
        if (!this.UserList.Exists(x => x.Id == i_User.Id))
        {
            this.UserList.Add(i_User);
            this.SetUserPassword();
        }
        else
        {
            .
            .
            .
        }
    }
}

also, if my description i correct, would that make any class who has any kind of member into a proxy pattern class??

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523

1 Answers1

3

No, this is not a valid implementation of a proxy pattern, because the crucial feature of that pattern implementation is missing: the proxy of an object needs to pretend it's the thing that it is proxying, either by providing the same interface, or by providing implicit conversions to the proxied object.

If ListUsers implemented IList<User> interface, it would be a proxy for List<User>. Similarly, if ListUsers let you obtain a special subclass of User that lets you read the data but not write it, that special class would be a proxy for the User.

.NET uses the proxy pattern in several notable places, such as managing list access through List<T>.AsReadOnly, or the Synchronized wrappers of HashTable and ArrayList.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • thank you, could you please elaborate more on the "Subclass of User" part? – Idan Boadana Aug 08 '13 at 01:36
  • @IdanBoadana Imagine class `ReadOnlyUser` subclass of `User` that is private to `ListUsers`, holds a reference to an actual user from the list, and forwards all read operations of the `User` base class to the wrapped user. All operations that would change the user, however, throw an exception. If `ListUsers` returned `ReadOnlyUser` wrapping the corresponding user, `ReadOnlyUser` would serve as a proxy to the real `User`. Of course in production situations both `User` and `ReadOnlyUser` would implement the same interface `IUser` rather than subclassing, but the overall approach would remain. – Sergey Kalinichenko Aug 08 '13 at 01:53