当前位置:首页 > Java

java如何运用模式

2026-03-23 18:27:06Java

Java设计模式的应用

Java设计模式是解决常见软件设计问题的可重用方案,分为创建型、结构型和行为型三大类。以下是一些常用设计模式及其在Java中的实现方式:

单例模式(Singleton)

确保一个类只有一个实例,并提供全局访问点。适用于配置管理、线程池等场景。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

工厂模式(Factory)

定义一个创建对象的接口,让子类决定实例化哪个类。适用于需要根据不同条件创建不同对象的场景。

public interface Shape {
    void draw();
}

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

public class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        }
        return null;
    }
}

观察者模式(Observer)

定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会得到通知并自动更新。适用于事件处理系统。

public interface Observer {
    void update(String message);
}

public class ConcreteObserver implements Observer {
    @Override
    public void update(String message) {
        System.out.println("Received: " + message);
    }
}

public class Subject {
    private List<Observer> observers = new ArrayList<>();

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

策略模式(Strategy)

定义一系列算法,将每个算法封装起来,并使它们可以互相替换。适用于需要动态切换算法或行为的场景。

public interface PaymentStrategy {
    void pay(int amount);
}

public class CreditCardPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paying " + amount + " via Credit Card");
    }
}

public class PaymentContext {
    private PaymentStrategy strategy;

    public void setStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void executePayment(int amount) {
        strategy.pay(amount);
    }
}

装饰器模式(Decorator)

动态地给一个对象添加额外的职责,相比继承更加灵活。适用于需要扩展功能但不想修改原有代码的场景。

public interface Coffee {
    double getCost();
    String getDescription();
}

public class SimpleCoffee implements Coffee {
    @Override
    public double getCost() {
        return 1.0;
    }

    @Override
    public String getDescription() {
        return "Simple coffee";
    }
}

public class MilkDecorator implements Coffee {
    private Coffee coffee;

    public MilkDecorator(Coffee coffee) {
        this.coffee = coffee;
    }

    @Override
    public double getCost() {
        return coffee.getCost() + 0.5;
    }

    @Override
    public String getDescription() {
        return coffee.getDescription() + ", milk";
    }
}

适配器模式(Adapter)

将一个类的接口转换成客户希望的另一个接口,使原本不兼容的类可以一起工作。适用于整合遗留代码或第三方库。

java如何运用模式

public interface ModernPrinter {
    void printDocument(String document);
}

public class LegacyPrinter {
    public void print(String text) {
        System.out.println("Legacy printer: " + text);
    }
}

public class PrinterAdapter implements ModernPrinter {
    private LegacyPrinter legacyPrinter;

    public PrinterAdapter(LegacyPrinter legacyPrinter) {
        this.legacyPrinter = legacyPrinter;
    }

    @Override
    public void printDocument(String document) {
        legacyPrinter.print(document);
    }
}

在实际应用中,应根据具体需求选择合适的设计模式。设计模式不是银弹,过度使用可能导致代码复杂度增加。合理运用设计模式可以提高代码的可维护性、可扩展性和可重用性。

标签: 模式java
分享给朋友:

相关文章

java如何输入数据

java如何输入数据

输入数据的方法 在Java中,输入数据可以通过多种方式实现,具体取决于输入来源(如控制台、文件、网络等)。以下是几种常见的方法: 使用Scanner类从控制台输入 Scanner类是Java中最常用…

java如何遍历map

java如何遍历map

遍历Map的几种方法 在Java中,遍历Map有多种方式,可以根据需求选择合适的方法。以下是常见的几种遍历方式: 使用entrySet遍历 通过entrySet()方法获取键值对的集合,可以同时访问…

如何选择java培训

如何选择java培训

评估培训机构资质 选择有正规资质的机构,查看其营业执照、办学许可证等。优先考虑具备人力资源和社会保障部或教育部认证的机构,这类机构的教学质量和课程设置通常更规范。 考察课程内容与行业需求匹配度…

java中如何获取当前时间

java中如何获取当前时间

获取当前时间的几种方法 使用 java.time 包(Java 8及以上推荐) import java.time.LocalDateTime; LocalDateTime currentTime =…

如何导入java项目

如何导入java项目

导入Java项目的方法 使用IDE导入(如IntelliJ IDEA或Eclipse) 打开IDE后选择导入现有项目,导航至项目根目录(包含pom.xml或build.gradle的文件位置)。IDE…

vue路由模式实现

vue路由模式实现

Vue 路由模式的实现方法 Vue Router 提供了两种主要的路由模式:hash 模式和 history 模式。以下是它们的实现方式和区别。 hash 模式 hash 模式使用 URL 的 ha…