Programming Foundations: Design Patterns
Fundamentals properties of Object-Oriented Design
Design Patterns provide paths to solutions for some of the most common object-oriented design conundrums.
Design Principles | Design Patterns |
---|---|
General guidelines | Specific Solutions |
Encapsulate your varies
Identify the aspects of your application that vary and separate them from what stays the same.
- if some aspect of your code is changing , that’s a sign you should pull it out and separate it
- By separating out the parts of your code that change, you can extend or alter them without affecting the rest of your code
- This principle is fundamental to almost every design pattern
Principle | Pattern |
---|---|
Encapsulate what varies | The Strategy Pattern |
The Iterator Pattern | |
The Factory Pattern | |
Loose Coopling | The Observe Pattern |
Loose Coupling
Strive for loosely coupled designs between objects that interact.Objects are loosely coupled when they interact with one another, which makes them coupled, but they don’t know a lot about each other, which makes them loosely coupled.
Program to an interface, NOT an Implementation
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
The Strategy Pattern
This Pattern defines a family of algorithms, encapsulate each one, and makes them interchangeable.
This lets the algorithm vary independently clients that use it.
We’re using a HAS-A relationship
Instead of inheriting behavior, we’re composing it
Favor Composition over Inheritance
Classes should achieve code reuse using composition rather than inheritance from a superclass.
The Adapter class handles the work of translating the request to the new Vendor class.
The Adapter Pattern
This Pattern converts the interface of a class into another interface that clients expect.
It allows classes to work together that couldn’t otherwise because of incompatible interfaces.
Adapters Use Composition
- The client is composed with the class with the target interface
- The adapter is composed with the adaptee
- The adapter delegates calls to the adaptee, and returns any needed value
The Observer Pattern
This Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its
dependents are notified and updated automatically.
Loose Coupling
Subjects and observers are loosely coupled
They interact, but have little knowledge of each other
Subject knows only that the observer implements a specific interface
Subject doesn’t know need to know the concrete class of the obe
There are threads about the Observer Pattern
Links and a paper about it:
And Java in its 9 version, deprecated java.util.Observer.