java 设计模式有哪些,不同的设计模式应用是什么,提供一下相关的代码示例
时间: 2023-07-25 09:46:11 浏览: 105
JAVA中几种设计模式的例子
Java 设计模式是基于面向对象编程思想的一套经验总结,主要用于解决软件设计中的一些常见问题,提高代码的可复用性、可维护性和可扩展性。常见的 Java 设计模式包括但不限于以下几种:
1. 工厂模式(Factory Pattern):用于创建对象,将对象的创建过程和客户端代码分离,使得客户端代码无需知道具体的创建过程,只需要知道创建的对象的类型即可。
示例代码:
```java
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("画了一个圆形");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("画了一个矩形");
}
}
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;
}
}
public class Demo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("CIRCLE");
circle.draw();
Shape rectangle = shapeFactory.getShape("RECTANGLE");
rectangle.draw();
}
}
输出:
画了一个圆形
画了一个矩形
```
2. 单例模式(Singleton Pattern):确保一个类只有一个实例,并提供全局访问点。
示例代码:
```java
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Demo {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // true
}
}
```
3. 适配器模式(Adapter Pattern):用于将一个类的接口转换成另一个接口,使得原本不兼容的类可以一起工作。
示例代码:
```java
interface MediaPlayer {
void play(String audioType, String fileName);
}
interface AdvancedMediaPlayer {
void playVlc(String fileName);
void playMp4(String fileName);
}
class VlcPlayer implements AdvancedMediaPlayer {
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file. Name: "+ fileName);
}
@Override
public void playMp4(String fileName) {
// do nothing
}
}
class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
// do nothing
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file. Name: "+ fileName);
}
}
class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
if(audioType.equalsIgnoreCase("vlc") ){
advancedMusicPlayer = new VlcPlayer();
} else if (audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
}else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
class AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("mp3")){
System.out.println("Playing mp3 file. Name: "+ fileName);
} 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 Demo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
audioPlayer.play("avi", "mind me.avi");
}
}
输出:
Playing mp3 file. Name: beyond the horizon.mp3
Playing mp4 file. Name: alone.mp4
Playing vlc file. Name: far far away.vlc
Invalid media. avi format not supported
```
4. 装饰器模式(Decorator Pattern):动态地给一个对象添加一些额外的职责,而不需要通过继承来实现。
示例代码:
```java
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("画了一个圆形");
}
}
abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
public void draw() {
decoratedShape.draw();
}
}
class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color: Red");
}
}
public class Demo {
public static void main(String[] args) {
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
circle.draw();
redCircle.draw();
redRectangle.draw();
}
}
输出:
画了一个圆形
画了一个圆形
Border Color: Red
画了一个矩形
Border Color: Red
```
5. 观察者模式(Observer Pattern):定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。
示例代码:
```java
import java.util.ArrayList;
import java.util.List;
interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}
class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyObservers();
}
@Override
public void attach(Observer observer) {
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
interface Observer {
void update();
}
class ConcreteObserver implements Observer {
private ConcreteSubject subject;
public ConcreteObserver(ConcreteSubject subject) {
this.subject = subject;
subject.attach(this);
}
@Override
public void update() {
System.out.println("观察者收到了新的通知,状态改变为:" + subject.getState());
}
}
public class Demo {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
new ConcreteObserver(subject);
new ConcreteObserver(subject);
new ConcreteObserver(subject);
System.out.println("第一次改变状态为:10");
subject.setState(10);
System.out.println("第二次改变状态为:20");
subject.setState(20);
}
}
输出:
第一次改变状态为:10
观察者收到了新的通知,状态改变为:10
观察者收到了新的通知,状态改变为:10
观察者收到了新的通知,状态改变为:10
第二次改变状态为:20
观察者收到了新的通知,状态改变为:20
观察者收到了新的通知,状态改变为:20
观察者收到了新的通知,状态改变为:20
```
阅读全文