Java 中常用的设计模式有很多种,其实平常用到的还比较少,但是还是有必要了解一下,可以按照实际情况运用到我们的代码中。按照类型可以基本分解为,创建型模式、结构型模式和行为型模式。
定义一个创建对象的接口,但是将实际的创建工作交给子类来实现。
考虑一个简单的工厂方法,生产不同类型的形状对象:
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
return null;
}
}
提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
考虑一个抽象工厂,生产不同类型的形状和颜色对象的组合:
interface Shape {
void draw();
}
interface Color {
void fill();
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
class Blue implements Color {
@Override
public void fill() {
System.out.println("Inside Blue::fill() method.");
}
}
abstract class AbstractFactory {
abstract Shape getShape(String shapeType);
abstract Color getColor(String colorType);
}
class ShapeFactory extends AbstractFactory {
@Override
Shape getShape(String shapeType) {
if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
return null;
}
@Override
Color getColor(String colorType) {
return null;
}
}
class ColorFactory extends AbstractFactory {
@Override
Shape getShape(String shapeType) {
return null;
}
@Override
Color getColor(String colorType) {
if (colorType.equalsIgnoreCase("BLUE")) {
return new Blue();
}
return null;
}
}
将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
考虑一个简单的食物构建器,可以构建汉堡和冷饮:
class Burger {
private String size;
private boolean cheese;
private boolean pepperoni;
private boolean lettuce;
public Burger(BurgerBuilder builder) {
this.size = builder.size;
this.cheese = builder.cheese;
this.pepperoni = builder.pepperoni;
this.lettuce = builder.lettuce;
}
static class BurgerBuilder {
private String size;
private boolean cheese;
private boolean pepperoni;
private boolean lettuce;
public BurgerBuilder(String size) {
this.size = size;
}
public BurgerBuilder cheese(boolean cheese) {
this.cheese = cheese;
return this;
}
public BurgerBuilder pepperoni(boolean pepperoni) {
this.pepperoni = pepperoni;
return this;
}
public BurgerBuilder lettuce(boolean lettuce) {
this.lettuce = lettuce;
return this;
}
public Burger build() {
return new Burger(this);
}
}
}
确保一个类只有一个实例,并提供一个全局访问点。
实现一个线程安全的懒汉式单例:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
将一个类的接口转换成客户端希望的另一个接口。
使用适配器让美国插头可以插入英国插座:
interface UKPlug {
void provideElectricity();
}
class UKSocket implements UKPlug {
@Override
public void provideElectricity() {
System.out.println("Providing electricity with UK plug.");
}
}
interface USPlug {
void supplyElectricity();
}
class USPlugConnector implements USPlug {
@Override
public void supplyElectricity() {
System.out.println("Supplying electricity with US plug.");
}
}
class USPlugAdapter implements UKPlug {
private USPlug plug;
public USPlugAdapter(USPlug plug) {
this.plug = plug;
}
@Override
public void provideElectricity() {
plug.supplyElectricity();
}
}
将抽象部分与它的实现部分分离,使它们可以独立地变化。
将不同颜色的笔与不同类型的绘图设备连接起来:
interface DrawAPI {
void draw();
}
abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
abstract void draw();
}
class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
void draw() {
drawAPI.draw();
}
}
将对象组合成树形结构以表示“部分-整体”的层次结构。
用组合模式表示员工的层级结构:
import java.util.ArrayList;
import java.util.List;
class Employee {
private String name;
private String dept;
private int salary;
private List subordinates;
public Employee(String name, String dept, int sal) {
this.name = name;
this.dept = dept;
this.salary = sal;
subordinates = new ArrayList();
}
public void add(Employee e) {
subordinates.add(e);
}
public void remove(Employee e) {
subordinates.remove(e);
}
public List getSubordinates() {
return subordinates;
}
@Override
public String toString() {
return ("Employee :[ Name : " + name + ", dept : " + dept + ", salary :" + salary + " ]");
}
}
定义对象间的一对多依赖关系,当一个对象状态发生改变时,它的所有依赖者都会收到通知并自动更新。
实现一个简单的气象站,当气象数据发生变化时,通知所有注册的观察者:
import java.util.ArrayList;
import java.util.List;
interface Observer {
void update(float temperature, float humidity, float pressure);
}
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
class WeatherData implements Subject {
private List observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
observers = new ArrayList<>();
}
public void registerObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperature, humidity, pressure);
}
}
public void measurementsChanged() {
notifyObservers();
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
}
允许对象在内部状态改变时改变它的行为。
使用状态模式实现一个简单的电梯控制系统:
interface State {
void doAction(Context context);
}
class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public State getState() {
return state;
}
}
class StartState implements State {
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
public String toString() {
return "Start State";
}
}
定义一系列算法,将每一个算法封装起来,并使它们可以互相替换。
实现一个简单的排序器,可以根据不同的策略选择不同的排序算法:
import java.util.List;
interface SortStrategy {
> void sort(List items);
}
class BubbleSortStrategy implements SortStrategy {
public > void sort(List items) {
// 实现冒泡排序算法
}
}
class QuickSortStrategy implements SortStrategy {
public > void sort(List items) {
// 实现快速排序算法
}
}
class Sorter {
private SortStrategy strategy;
public Sorter(SortStrategy strategy) {
this.strategy = strategy;
}
public > void sort(List items) {
strategy.sort(items);
}
}
这只是一些常见的设计模式,Java一共有23种设计模式,实际掌握几种设计模式就可以帮助你更好地组织代码、提高代码的可维护性和可扩展性。