Java23种设计模式详解

Java作为目前最流行的编程语言之一,其设计模式的应用也越来越广泛。设计模式是指在软件设计过程中,经过实践证明的一些最佳的解决方案。Java23种设计模式可以分为三类:创建型模式、结构型模式和行为型模式。

一、创建型模式

创建型模式主要关注对象的创建和管理,包括以下5种模式:

1. 工厂方法模式

工厂方法模式是指定义一个工厂接口,由子类来实现工厂接口中的方法,并由子类来创建对象。这种模式可以避免直接使用new关键字创建对象的方式,增强了代码的可扩展性。

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();
    }
}

2. 抽象工厂模式

抽象工厂模式是指定义一个抽象工厂接口,由子类来实现抽象工厂接口中的方法,并由子类来创建一组相关的对象。这种模式可以避免直接使用new关键字创建对象的方式,增强了代码的可扩展性。

public interface AnimalFactory {
    Animal createDog();
    Animal createCat();
}

public class WhiteAnimalFactory implements AnimalFactory {
    public Animal createDog() {
        return new WhiteDog();
    }
    public Animal createCat() {
        return new WhiteCat();
    }
}

public class BlackAnimalFactory implements AnimalFactory {
    public Animal createDog() {
        return new BlackDog();
    }
    public Animal createCat() {
        return new BlackCat();
    }
}

3. 单例模式

单例模式是指一个类只有一个实例,并且该实例提供了一个访问它的全局访问点。这种模式可以保证在程序中只有一个实例,从而节省内存空间,提高程序的性能。

public class Singleton {
    private static Singleton instance = null;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

4. 建造者模式

Java23种设计模式详解

建造者模式是指将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。这种模式可以简化对象的构造过程,提高代码的可读性。

public class Person {
    private String name;
    private int age;
    private String gender;
    private String address;
    
    public static class Builder {
        private String name;
        private int age;
        private String gender;
        private String address;
        
        public Builder(String name, int age) {
            this.name = name;
            this.age = age;
        }
        
        public Builder gender(String gender) {
            this.gender = gender;
            return this;
        }
        
        public Builder address(String address) {
            this.address = address;
            return this;
        }
        
        public Person build() {
            return new Person(this);
        }
    }
    
    private Person(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.gender = builder.gender;
        this.address = builder.address;
    }
}

5. 原型模式

原型模式是指通过复制一个已经存在的实例来创建新的实例。这种模式可以避免直接使用new关键字创建对象的方式,提高了代码的可扩展性。

public abstract class Shape implements Cloneable {
    private String id;
    protected String type;
    
    public String getId() {
        return id;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String type) {
        this.type = type;
    }
    
    public abstract void draw();
    
    public Object clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

public class Circle extends Shape {
    public Circle() {
        type = "Circle";
    }
    
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}

public class Square extends Shape {
    public Square() {
        type = "Square";
    }
    
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}

public class ShapeCache {
    private static Map shapeMap = new HashMap();
    
    public static Shape getShape(String shapeId) {
        Shape cachedShape = shapeMap.get(shapeId);
        return (Shape) cachedShape.clone();
    }
    
    public static void loadCache() {
        Circle circle = new Circle();
        circle.setId("1");
        shapeMap.put(circle.getId(), circle);
        
        Square square = new Square();
        square.setId("2");
        shapeMap.put(square.getId(), square);
    }
}

二、结构型模式

结构型模式主要关注对象的组合和协作,包括以下7种模式:

1. 适配器模式

适配器模式是指将一个类的接口转换成客户希望的另一个接口。这种模式可以使得原本由于接口不兼容而不能一起工作的类可以在一起工作。

public interface AdvancedMediaPlayer {
    public void playVlc(String fileName);
    public void playMp4(String fileName);
}

public class VlcPlayer implements AdvancedMediaPlayer {
    public void playVlc(String fileName) {
        System.out.println("Playing vlc file. Name: " + fileName);
    }
    public void playMp4(String fileName) {}
}

public class Mp4Player implements AdvancedMediaPlayer {
    public void playVlc(String fileName) {}
    public void playMp4(String fileName) {
        System.out.println("Playing mp4 file. Name: " + fileName);
    }
}

public interface MediaPlayer {
    public void play(String audioType, String fileName);
}

public 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();
        }	
    }
    
    public void play(String audioType, String fileName) {
        if(audioType.equalsIgnoreCase("vlc")){
            advancedMusicPlayer.playVlc(fileName);
        }else if(audioType.equalsIgnoreCase("mp4")){
            advancedMusicPlayer.playMp4(fileName);
        }
    }
}

public class AudioPlayer implements MediaPlayer {
    MediaAdapter mediaAdapter; 
    
    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");
        }
    }
}

2. 桥接模式

桥接模式是指将抽象部分与实现部分分离,使它们可以独立地变化。这种模式可以避免系统在多个维度上的复杂性。

public interface DrawAPI {
    public void drawCircle(int radius, int x, int y);
}

public class RedCircle implements DrawAPI {
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]");
    }
}

public class GreenCircle implements DrawAPI

本文来源:词雅网

本文地址:https://www.ciyawang.com/y4gale.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐