Design Patterns
Design patterns are standardized solutions to recurring design problems in object-oriented systems. They capture best practices and provide a common language for software developers to discuss and apply design principles.
Some commonly used design patterns include:
- Singleton Pattern: Ensures that a class has only one instance, and provides a global point of access to that instance.
- Factory Pattern: Provides an interface for creating objects, but allows subclasses to decide which class to instantiate.
- Adapter Pattern: Allows objects with incompatible interfaces to work together by creating a common interface that both objects can use.
- Decorator Pattern: Allows behavior to be added to an individual object dynamically, without affecting the behavior of other objects. It provides a flexible alternative to subclassing for extending functionality.
Design patterns are not specific to any programming language and can be applied to any object-oriented system. They can improve code reusability, readability, and maintainability.
Let's take a look at an example of the Decorator pattern in Java:
xxxxxxxxxx
41
}
// Decorator pattern example
interface Beverage {
String getDescription();
double getCost();
}
class Espresso implements Beverage {
public String getDescription() {
return "Espresso";
}
public double getCost() {
return 1.99;
}
}
class Milk implements Beverage {
private Beverage beverage;
public Milk(Beverage beverage) {
this.beverage = beverage;
}
public String getDescription() {
return beverage.getDescription() + ", Milk";
}
public double getCost() {
return beverage.getCost() + 0.49;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment