摘要:,,本文介绍了Java常用设计模式的实例详解,包括实例图和详细解释。这些设计模式有助于解决软件开发中常见的问题,提高代码的可维护性和可重用性。文章通过实例图的方式,让读者更加直观地理解设计模式的实现方式,从而更好地掌握Java编程中的最佳实践。这些设计模式包括抽象工厂模式、建造者模式、单例模式、适配器模式等。通过阅读本文,读者可以深入了解这些设计模式的原理和应用场景,提高Java编程水平。

二、单例模式(Singleton Pattern)

单例模式是一种创建型模式,它确保一个类只有一个实例,并提供一个全局访问点,在Java中,单例模式可以通过饿汉式、懒汉式、双重检查锁等方式实现。

实例:饿汉式单例模式

public class Singleton {
    private static Singleton instance = new Singleton(); // 饿汉式,类加载时就实例化
    private Singleton() {} // 私有化构造方法
    
    public static Singleton getInstance() { // 提供全局访问点
        return instance;
    }
}

三、工厂模式(Factory Pattern)

工厂模式是一种创建型模式,它提供了一种创建对象的最佳方式,在Java中,工厂模式分为简单工厂模式、工厂方法模式和抽象工厂模式。

实例:简单工厂模式

假设我们有一个产品接口Product和几个实现类ProductAProductB等,我们可以创建一个简单工厂类Factory来创建这些产品对象。

public interface Product {
    void use();
}
public class ProductA implements Product {
    public void use() {
        System.out.println("ProductA in use.");
    }
}
public class Factory {
    public Product createProduct(String type) { 
        if ("A".equals(type)) {
            return new ProductA();
        } else { 
            // 其他产品创建逻辑... 
            return null; // 默认返回null或其他默认值
        }
    }
}

示例使用:

Factory factory = new Factory(); 
Product product = factory.createProduct("A"); 
product.use(); // 输出 "ProductA in use."

四、建造者模式(Builder Pattern)

建造者模式是一种创建型模式,允许构造复杂对象时逐步构建每个部分。

实例:一个简单的手机建造者模式

public class PhoneBuilder { 
    private StringBuilder model = new StringBuilder(); 
    public PhoneBuilder withScreenSize(int size) { 
        model.append("Screen Size: ").append(size); 
        return this; // 支持链式调用 
    } 
    public PhoneBuilder withCamera(int megapixels) { 
        model.append("Camera: ").append(megapixels).append(" MP"); 
        return this; // 支持链式调用 
    } 
    public Phone build() { 
        return new Phone(model.toString()); // 构建并返回Phone对象 
    } 
} 
public static void main(String[] args) { 
    Phone phone = new PhoneBuilder().withScreenSize(6.5).withCamera(48).build(); // 使用建造者模式构建Phone对象 
}
```五、策略模式(Strategy Pattern)策略模式是一种行为型模式,它定义了一系列可以互相替换的算法,并使得算法的选择与使用相互独立,实例:排序策略public interface SortStrategy { void sort(int[] array);} public class BubbleSort implements SortStrategy { public void sort(int[] array) { //冒泡排序逻辑... }} public class QuickSort implements SortStrategy { public void sort(int[] array) { //快速排序逻辑... }} public class Context { private SortStrategy strategy; public Context(SortStrategy strategy) { this.strategy = strategy; } public void executeSorting(int[] array) { strategy.sort(array); } public static void main(String[] args) { Context context = new Context(new BubbleSort()); context.executeSorting(new int[]{5, 2, 9}); //使用冒泡排序策略 context = new Context(new QuickSort()); context.executeSorting(new int[]{5, 2, 9}); //使用快速排序策略 }本文介绍了Java中几种常见的设计模式及其实例,包括单例模式、工厂模式、建造者模式和策略模式等,这些设计模式有助于我们编写更加灵活、可维护和可复用的代码,在实际开发中,我们可以根据具体需求选择合适的设计模式来提高代码质量,希望本文能对读者有所帮助。

Java常用设计模式实例详解 java常用设计模式实例图 1

声明:本站所有文章均摘自网络。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。