设计模式在Java中的应用:提升代码质量与可维护性!
开篇语
哈喽,各位小伙伴们,你们好呀,我是喵手。运营社区:C站/掘金/腾讯云/阿里云/华为云/51CTO;欢迎大家常来逛逛
今天我要给大家分享一些自己日常学习到的一些知识点,并以文字的形式跟大家一起交流,互相学习,一个人虽可以走的更快,但一群人可以走的更远。
我是一名后端开发爱好者,工作日常接触到最多的就是Java语言啦,所以我都尽量抽业余时间把自己所学到所会的,通过文章的形式进行输出,希望以这种方式帮助到更多的初学者或者想入门的小伙伴们,同时也能对自己的技术进行沉淀,加以复盘,查缺补漏。
小伙伴们在批阅的过程中,如果觉得文章不错,欢迎点赞、收藏、关注哦。三连即是对作者我写作道路上最好的鼓励与支持!
前言
设计模式是软件开发中的一套标准解决方案,用于解决常见的开发问题。它们提供了一些通用的最佳实践,能够帮助开发者设计出更高效、可扩展、易维护的程序。Java作为一门面向对象编程语言,深刻体现了设计模式的应用。掌握设计模式,不仅能够帮助我们解决实际的编程问题,还能使我们的代码更加简洁、模块化。
本文将详细介绍五种常见的设计模式在Java中的应用:单例模式、工厂模式、抽象工厂模式、观察者模式、装饰器模式和策略模式。我们将通过实际代码示例来演示每个设计模式的用法和优点。
1. 单例模式的多种实现:确保类只有一个实例
单例模式简介
单例模式(Singleton Pattern)是一种常见的设计模式,确保某个类只有一个实例,并提供一个全局访问点。单例模式广泛应用于需要全局共享资源的场景,如数据库连接池、日志管理器等。
单例模式的实现方式:
1. 饿汉式单例(线程安全)
在类加载时就创建单例对象,保证类加载时就创建唯一的实例。
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return INSTANCE;
}
}
2. 懒汉式单例(线程不安全)
延迟实例化,直到第一次调用getInstance()
时才创建实例。
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton(); // 非线程安全
}
return instance;
}
}
3. 双重检查锁定(线程安全)
结合了懒汉式和饿汉式的优点,使用volatile
关键字和双重检查来确保线程安全和延迟实例化。
public class Singleton {
private static volatile Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
4. 枚举式单例(推荐)
通过枚举类型实现单例,避免了多线程和反序列化攻击的问题。
public enum Singleton {
INSTANCE;
public void doSomething() {
System.out.println("Doing something");
}
}
2. 工厂模式和抽象工厂模式:创建对象的设计模式
工厂模式(Factory Pattern)
工厂模式通过定义一个创建对象的接口,但由子类决定实例化哪个类。它可以帮助我们在不修改代码的情况下,灵活地引入新的产品。
简单工厂模式:
工厂类根据传入的参数决定创建哪种产品对象。
public class AnimalFactory {
public static Animal createAnimal(String type) {
if (type.equals("Dog")) {
return new Dog();
} else if (type.equals("Cat")) {
return new Cat();
}
return null;
}
}
public interface Animal {
void speak();
}
public class Dog implements Animal {
public void speak() {
System.out.println("Woof!");
}
}
public class Cat implements Animal {
public void speak() {
System.out.println("Meow!");
}
}
工厂方法模式:
通过工厂方法来创建对象,避免在create
方法中硬编码具体类。
public interface AnimalFactory {
Animal createAnimal();
}
public class DogFactory implements AnimalFactory {
public Animal createAnimal() {
return new Dog();
}
}
public class CatFactory implements AnimalFactory {
public Animal createAnimal() {
return new Cat();
}
}
抽象工厂模式(Abstract Factory Pattern)
抽象工厂模式提供了一个接口,用于创建一系列相关或依赖的对象,而无需指定它们的具体类。适用于需要创建一组产品对象时。
示例:
public interface AnimalFactory {
Animal createAnimal();
Food createFood();
}
public interface Animal {
void speak();
}
public interface Food {
void eat();
}
public class DogFactory implements AnimalFactory {
public Animal createAnimal() {
return new Dog();
}
public Food createFood() {
return new Bone();
}
}
public class Dog implements Animal {
public void speak() {
System.out.println("Woof!");
}
}
public class Bone implements Food {
public void eat() {
System.out.println("Crunch!");
}
}
3. 观察者模式:事件驱动型设计模式
观察者模式简介
观察者模式(Observer Pattern)是一种行为型设计模式,定义了对象之间一对多的依赖关系,使得当一个对象的状态发生改变时,其相关依赖对象(观察者)会自动接收到通知并做出响应。
例子:
public interface Observer {
void update(String message);
}
public class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
public class TestObserver {
public static void main(String[] args) {
Subject subject = new Subject();
Observer observer1 = new ConcreteObserver("Observer1");
Observer observer2 = new ConcreteObserver("Observer2");
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notifyObservers("Hello, observers!");
}
}
4. 装饰器模式:为对象动态添加功能
装饰器模式简介
装饰器模式(Decorator Pattern)是一种结构型设计模式,用于动态地为对象添加额外的功能。它通常通过继承来扩展原有类的功能,同时保持原有类的功能不变。
示例:
public interface Coffee {
double cost();
}
public class SimpleCoffee implements Coffee {
public double cost() {
return 5;
}
}
public class MilkDecorator implements Coffee {
private Coffee coffee;
public MilkDecorator(Coffee coffee) {
this.coffee = coffee;
}
public double cost() {
return coffee.cost() + 2;
}
}
public class SugarDecorator implements Coffee {
private Coffee coffee;
public SugarDecorator(Coffee coffee) {
this.coffee = coffee;
}
public double cost() {
return coffee.cost() + 1;
}
}
public class TestDecorator {
public static void main(String[] args) {
Coffee coffee = new SimpleCoffee();
System.out.println("Cost: " + coffee.cost());
coffee = new MilkDecorator(coffee);
System.out.println("Cost with milk: " + coffee.cost());
coffee = new SugarDecorator(coffee);
System.out.println("Cost with milk and sugar: " + coffee.cost());
}
}
5. 策略模式:定义一系列算法并使其可互换
策略模式简介
策略模式(Strategy Pattern)是一种行为型设计模式,它定义了一系列的算法,将每个算法封装起来,并使它们可以互换。策略模式让算法独立于使用它的客户端而变化。
示例:
public interface PaymentStrategy {
void pay(int amount);
}
public class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card");
}
}
public class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal");
}
}
public class PaymentContext {
private PaymentStrategy strategy;
public PaymentContext(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void executePayment(int amount) {
strategy.pay(amount);
}
}
public class TestStrategy {
public static void main(String[] args) {
PaymentContext context = new PaymentContext(new CreditCardPayment());
context.executePayment(100);
context = new PaymentContext(new PayPalPayment());
context.executePayment(200);
}
}
结语:设计模式的应用提升软件开发水平
设计模式是一种解决常见问题的有效工具,能够帮助开发者在面对复杂需求时作出更合适的设计决策。通过理解和应用单例模式、工厂模式、抽象工厂模式、观察者模式、装饰器模式和策略模式,我们可以编写出更加灵活、可维护、可扩展的代码。掌握这些设计模式,将大大提升我们的编程能力和解决问题的效率。
… …
文末
好啦,以上就是我这期的全部内容,如果有任何疑问,欢迎下方留言哦,咱们下期见。
… …
学习不分先后,知识不分多少;事无巨细,当以虚心求教;三人行,必有我师焉!!!
wished for you successed !!!
⭐️若喜欢我,就请关注我叭。
⭐️若对您有用,就请点赞叭。
⭐️若有疑问,就请评论留言告诉我叭。
版权声明:本文由作者原创,转载请注明出处,谢谢支持!
- 点赞
- 收藏
- 关注作者
评论(0)