How do the Proxy, Decorator, Adapter, and Bridge P

2019-01-01 09:43发布

I was looking at the Proxy Pattern, and to me it seems an awful lot like the Decorator, Adapter, and Bridge patterns. Am I misunderstanding something? What's the difference? Why would I use the Proxy pattern versus the others? How have you used them in the past in real world projects?

13条回答
皆成旧梦
2楼-- · 2019-01-01 10:21

All good answers from experts have already explained what does each pattern stands for.

I will decorate key points.

Decorator:

  1. Add behaviour to object at run time. Inheritance is the key to achieve this functionality, which is both advantage and disadvantage of this pattern.
  2. It modifies the behaviour of interface.

e.g. (with chaining ) : java.io package classes related to InputStream & OutputStream interfaces

FileOutputStream fos1 = new FileOutputStream("data1.txt");  
ObjectOutputStream out1 = new ObjectOutputStream(fos1);

Proxy:

  1. Use it for lazy initialization, performance improvement by caching the object and controlling access to the client/caller. It may provide alternative behaviour or call real object. During this process, it may create new Object.
  2. Unlike Decorator, which allows chaining of objects, Proxy does not allow chaining.

e.g.: java.rmi package classes.

Adapter:

  1. It allows two unrelated interfaces to work together through the different objects, possibly playing same role.
  2. It modifies original interface.

e.g. java.io.InputStreamReader (InputStream returns a Reader)

Bridge:

  1. It allows both abstractions and implementations to vary independently.
  2. It uses composition over inheritance.

e.g. Collection classes in java.util. List implemented by ArrayList.

Key notes:

  1. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
  2. Adapter changes an object's interface, Decorator enhances an object's responsibilities.
  3. Decorator and Proxy have different purposes but similar structures
  4. Adapter makes things work after they're designed; Bridge makes them work before they are.
  5. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together
  6. Decorator is designed to let you add responsibilities to objects without subclassing.

Have a look at great SE questions/articles regarding examples of various design patterns

When to Use the Decorator Pattern?

When do you use the Bridge Pattern? How is it different from Adapter pattern?

Differences between Proxy and Decorator Pattern

查看更多
登录 后发表回答