🙈作者简介:练习时长两年半的Java up主
🙉个人主页:程序员老茶
🙊 ps:点赞👍是免费的,却可以让写博客的作者开心好久好久😎
📚系列专栏:Java全栈,计算机系列(火速更新中)
💭 格言:种一棵树最好的时间是十年前,其次是现在
🏡动动小手,点个关注不迷路,感谢宝子们一键三连
目录
- 课程名:Java
- 内容/作用:知识点/设计/实验/作业/练习
- 学习:Java设计模式
- Java设计模式
- 1. 创建型模式
- 1.1 简单工厂模式(Simple Factory Pattern)
- 1.2 工厂方法模式(Factory Method Pattern)
- 1.3 抽象工厂模式(Abstract Factory Pattern)
- 2. 结构型模式
- 2.1 适配器模式(Adapter Pattern)
- 2.2 装饰器模式(Decorator Pattern)
- 3. 行为型模式
- 3.1 观察者模式(Observer Pattern)
- 3.2 策略模式(Strategy Pattern)
课程名:Java
内容/作用:知识点/设计/实验/作业/练习
学习:Java设计模式
Java设计模式
1. 创建型模式
1.1 简单工厂模式(Simple Factory Pattern)
简单工厂模式通过一个工厂类来创建对象,根据不同的参数返回不同类的实例。
示例代码:
public interface Shape {void draw();
}public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a circle");}
}public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a rectangle");}
}public class ShapeFactory {public static Shape createShape(String shapeType) {if (shapeType.equalsIgnoreCase("circle")) {return new Circle();} else if (shapeType.equalsIgnoreCase("rectangle")) {return new Rectangle();}return null;}
}public class Main {public static void main(String[] args) {Shape circle = ShapeFactory.createShape("circle");circle.draw();Shape rectangle = ShapeFactory.createShape("rectangle");rectangle.draw();}
}
1.2 工厂方法模式(Factory Method Pattern)
工厂方法模式定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。
示例代码:
public interface Shape {void draw();
}public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a circle");}
}public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a rectangle");}
}public interface ShapeFactory {Shape createShape();
}public class CircleFactory implements ShapeFactory {@Overridepublic Shape createShape() {return new Circle();}
}public class RectangleFactory implements ShapeFactory {@Overridepublic Shape createShape() {return new Rectangle();}
}public class Main {public static void main(String[] args) {ShapeFactory circleFactory = new CircleFactory();Shape circle = circleFactory.createShape();circle.draw();ShapeFactory rectangleFactory = new RectangleFactory();Shape rectangle = rectangleFactory.createShape();rectangle.draw();}
}
1.3 抽象工厂模式(Abstract Factory Pattern)
抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
示例代码:
public interface Color {void fill();
}public class Red implements Color {@Overridepublic void fill() {System.out.println("Filling with red color");}
}public class Blue implements Color {@Overridepublic void fill() {System.out.println("Filling with blue color");}
}public interface Shape {void draw();
}public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a circle");}
}public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a rectangle");}
}public interface AbstractFactory {Color createColor();Shape createShape();
}public class RedCircleFactory implements AbstractFactory {@Overridepublic Color createColor() {return new Red();}@Overridepublic Shape createShape() {return new Circle();}
}public class BlueRectangleFactory implements AbstractFactory {@Overridepublic Color createColor() {return new Blue();}@Overridepublic Shape createShape() {return new Rectangle();}
}public class Main {public static void main(String[] args) {AbstractFactory redCircleFactory = new RedCircleFactory();Color red = redCircleFactory.createColor();red.fill();Shape circle = redCircleFactory.createShape();circle.draw();AbstractFactory blueRectangleFactory = new BlueRectangleFactory();Color blue = blueRectangleFactory.createColor();blue.fill();Shape rectangle = blueRectangleFactory.createShape();rectangle.draw();}
}
2. 结构型模式
2.1 适配器模式(Adapter Pattern)
适配器模式将一个类的接口转换为客户端所期望的另一个接口。它可以让原本不兼容的类合作无间。
示例代码:
public interface MediaPlayer {void play(String audioType, String fileName);
}public interface AdvancedMediaPlayer {void playVlc(String fileName);void playMp4(String fileName);
}public class VlcPlayer implements AdvancedMediaPlayer {@Overridepublic void playVlc(String fileName) {System.out.println("Playing vlc file: " + fileName);}@Overridepublic void playMp4(String fileName) {// Do nothing}
}public class Mp4Player implements AdvancedMediaPlayer {@Overridepublic void playVlc(String fileName) {// Do nothing}@Overridepublic void playMp4(String fileName) {System.out.println("Playing mp4 file: " + fileName);}
}public class MediaAdapter implements MediaPlayer {private AdvancedMediaPlayer advancedMediaPlayer;public MediaAdapter(String audioType) {if (audioType.equalsIgnoreCase("vlc")) {advancedMediaPlayer = new VlcPlayer();} else if (audioType.equalsIgnoreCase("mp4")) {advancedMediaPlayer = new Mp4Player();}}@Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase("vlc")) {advancedMediaPlayer.playVlc(fileName);} else if (audioType.equalsIgnoreCase("mp4")) {advancedMediaPlayer.playMp4(fileName);}}
}public class AudioPlayer implements MediaPlayer {private MediaAdapter mediaAdapter;@Overridepublic void play(String audioType, String fileName) {// 播放 mp3 音乐文件的内置支持if (audioType.equalsIgnoreCase("mp3")) {System.out.println("Playing mp3 file: " + fileName);}// 使用 MediaAdapter 来播放其他文件格式的音乐文件else if (audioType.equalsIgnoreCase("vlc")|| audioType.equalsIgnoreCase("mp4")) {mediaAdapter = new MediaAdapter(audioType);mediaAdapter.play(audioType, fileName);}else {System.out.println("Invalid media. " + audioType + " format not supported");}}
}public class Main {public static void main(String[] args) {MediaPlayer audioPlayer = new AudioPlayer();audioPlayer.play("mp3", "song.mp3");audioPlayer.play("vlc", "movie.vlc");audioPlayer.play("mp4", "video.mp4");audioPlayer.play("avi", "movie.avi");}
}
2.2 装饰器模式(Decorator Pattern)
装饰器模式动态地给一个对象添加一些额外的职责,同时又不改变其结构。
示例代码:
public interface Car {void assemble();
}public class BasicCar implements Car {@Overridepublic void assemble() {System.out.println("Basic Car.");}
}public abstract class CarDecorator implements Car {protected Car decoratedCar;public CarDecorator(Car decoratedCar){this.decoratedCar = decoratedCar;}public void assemble(){decoratedCar.assemble();}
}public class SportsCar extends CarDecorator {public SportsCar(Car decoratedCar) {super(decoratedCar);}@Overridepublic void assemble(){super.assemble();System.out.println("Adding features of Sports Car.");}
}public class LuxuryCar extends CarDecorator {public LuxuryCar(Car decoratedCar) {super(decoratedCar);}@Overridepublic void assemble(){super.assemble();System.out.println("Adding features of Luxury Car.");}
}public class Main {public static void main(String[] args) {Car basicCar = new BasicCar();Car sportsCar = new SportsCar(basicCar);sportsCar.assemble();Car luxurySportsCar = new LuxuryCar(new SportsCar(basicCar));luxurySportsCar.assemble();}
}
3. 行为型模式
3.1 观察者模式(Observer Pattern)
观察者模式定义了对象之间的一对多依赖关系,当一个对象状态发生改变时,其相关依赖对象都会收到通知并自动更新。
示例代码:
import java.util.ArrayList;
import java.util.List;interface Observer {void update(String message);
}class User implements Observer {private final String name;User(String name) {this.name = name;}@Overridepublic void update(String message) {System.out.println(name + " received message: " + message);}
}interface Subject {void registerObserver(Observer observer);void removeObserver(Observer observer);void notifyObservers(String message);
}class NewsAgency implements Subject {private final List<Observer> observers;private String news;NewsAgency() {this.observers = new ArrayList<>();}@Overridepublic void registerObserver(Observer observer) {observers.add(observer);}@Overridepublic void removeObserver(Observer observer) {observers.remove(observer);}@Overridepublic void notifyObservers(String message) {for (Observer observer : observers) {observer.update(message);}}public void setNews(String news) {this.news = news;notifyObservers(news);}
}class Main {public static void main(String[] args) {NewsAgency newsAgency = new NewsAgency();User user1 = new User("User 1");User user2 = new User("User 2");newsAgency.registerObserver(user1);newsAgency.registerObserver(user2);newsAgency.setNews("Breaking news!");newsAgency.removeObserver(user2);newsAgency.setNews("Important news!");}
}
3.2 策略模式(Strategy Pattern)
策略模式定义了一系列算法,将每个算法封装起来,使它们可以互相替换,使得算法可以独立于使用它的客户端而变化。
示例代码:
interface PaymentStrategy {void pay(double amount);
}class CreditCardStrategy implements PaymentStrategy {private final String name;private final String cardNumber;private final String cvv;private final String dateOfExpiry;CreditCardStrategy(String name, String cardNumber, String cvv, String dateOfExpiry) {this.name = name;this.cardNumber = cardNumber;this.cvv = cvv;this.dateOfExpiry = dateOfExpiry;}@Overridepublic void pay(double amount) {System.out.println(amount + " paid with credit/debit card");}
}class PayPalStrategy implements PaymentStrategy {private final String emailId;private final String password;PayPalStrategy(String emailId, String password) {this.emailId = emailId;this.password = password;}@Overridepublic void pay(double amount) {System.out.println(amount + " paid using PayPal.");}
}class ShoppingCart {private final List<Item> items;ShoppingCart() {this.items = new ArrayList<>();}void addItem(Item item) {items.add(item);}double calculateTotal() {double total = 0;for (Item item : items) {total += item.getPrice();}return total;}void pay(PaymentStrategy paymentStrategy) {double amount = calculateTotal();paymentStrategy.pay(amount);}
}class Item {private final String name;private final double price;Item(String name, double price) {this.name = name;this.price = price;}double getPrice() {return price;}
}class Main {public static void main(String[] args) {ShoppingCart cart = new ShoppingCart();Item item1 = new Item("Item 1", 20);Item item2 = new Item("Item 2", 30);cart.addItem(item1);cart.addItem(item2);cart.pay(new CreditCardStrategy("John Doe", "1234567890123456", "123", "12/2025"));cart.pay(new PayPalStrategy("john.doe@example.com", "password"));}
}
以上是一些常见的Java设计模式,每种设计模式都有不同的应用场景和用途。使用这些设计模式可以提高代码的可维护性、可扩展性和重用性。
往期专栏 |
---|
Java全栈开发 |
数据结构与算法 |
计算机组成原理 |
操作系统 |
数据库系统 |
物联网控制原理与技术 |