Вопрос

I read this post, but I need an expert opinion on Employ example from this post:

Decorator Pattern by Examples

enter image description here

Can we decorate classes with data members as well?

Please also share your feedback on this last questions as well.

Это было полезно?

Решение

Whenever you implement and aggregate an interface, using the aggregated object to provide part of the implemented functionality, you will have a decorator pattern. The post you linked matches that description and therefore it is a decorator pattern.

From Head First, Design Patterns:

The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality

NOTE: This definition is exactly the same that the one you can find in the GoF book: Design Patterns: Elements of Reusable Object-Oriented Software and the same that you find at the link you posted.

With your EmployeeDecorator subclasses you are adding services to Employee being this "intermediate" class (EmployeeDecorator) a way to encapsulate delegation at a parent class so concrete subclases such as TeamMember and TeamLead do not replicate the delegation code.

Другие советы

The usual purpose of the Decorator pattern is to wrap the implementations of individual methods of the decorated object with another implementation.

Both a decorated and an undecorated object are usually referred to through their common interface, so that the code which uses them doesn't need to know if the object is wrapped in a decorator or not and when it is wrapped which decorator(s) it uses. For that reason it is uncommon for a Decorator to add new public methods to the object which do not override any of the methods defined by the common interface.

Decorator is a behavioral pattern, i.e. it deals with the class methods that are defined by its interface and the last do not define any members, the pattern is irrelevant to them.

As per your question:

Can we decorate classes with data members as well?

Yes, we can decorate a class either with or without members.

However, if you plan using decoration as a substitution for inheritance and as a such have plans to access the members of the decorated class (in your example EmployeeImpl), that won't work for you, as a decorator actually decorates the interface rather than its implementation class.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top