Adapter (class level)
- Intent
- Convert the interface from one class to another
- Lets classes work together that aren’t
- Motivation
- Be able to change database, integrate new library without rewriting the entire application
- Entities
- Client: utilizes Target’s interface
- Target: interface used by a specific Client
- Adapter: adapts Adaptee interface to Target (adapt Target interfaces to Adaptee by proving a mapping between methods/function call)
- Adaptee: interface needing adapting
- Pro
- Reusable decoupling of interfaces
- Limitation
- Runtime overhead
- Overriding Adaptee is more difficult in general
// Target
class CTarget {
public:
CTarget();
virtual void Request();
}
// Adaptee
class CAdaptee {
public:
CAdaptee():
void SpecificRequest();
}
// Adapter
class CAdapter : public CTarget {
protected:
CAdaptee *DAdaptee;
public:
CAdapter() {
DAdaptee = new CAdaptee();
}
void Request() {
DAdaptee->SpecificRequest();
}
}
Decorator (object level)
- Intent
- Dynamically attach additional responsibilities to an object
- Flexible alternative to subclassing
- Motivation
- Add different properties to an object
- Benefits
- More flexible than inheritance
- Lot’s of little object that are easier to maintain
- Limitations
- Divide program in lot’s of little objects
// Component
class CComponent {
public:
virtual void Operation() = 0;
}
// Decorator
class CDecorator : CComponent {
protected:
CComponent *DComponent;
public:
CDecorator(CComponent *component) {
DComponent = component;
}
void Operation() {
DComponent->Operation();
}
}
// Concrete Decorator
class CConcreteDecorator : public CDecorator {
protected:
int DAdditionalState;
void AddedBehaveior();
public:
CConcreteDecorator(CComponent *component) : CDecorator(component) {
DAdditionalState = 0;
}
void Operation() {
CDecorator::Operation();
AddedBehaveior();
}
}
public interface Component {
int getPrice();
List<String> getParts();
}
public class BaseComponent implements Component {
public int getCost() {
return 0;
}
public List<String> getParts() {
return new ArrayList<>();
}
}
public BaseDecorator implements Component {
protected final Component c;
protected BaseDecorator(Component c) {
this.c = c;
}
public int getCost() {
return this.c.getCost();
}
public List<String> getParts() {
return this.c.getParts();
}
}
public Part1Decorator implements BaseDecorator {
protected Part1Decorator(Component c) {
super(c);
this.c = c;
}
public int getCost() {
super.getCost() + 10;
}
public List<String> getParts() {
List<String> currentParts = new ArrayList<>(super.getParts());
currentParts.Add("Part1");
return currentParts;
}
}
public class Part1 implements
Composite (object level)
- Intent
- Compose object in three structure to represent hierarchies
- Uniform treatment of individual and composite objects
- Motivation
- Benefits
- Limitations
Proxy (object level)
- What: It provides a more versatile and sophisticate reference to a simpler object
- Why