21xrx.com
2024-09-19 09:47:17 Thursday
登录
文章检索 我的文章 写文章
Java常用的设计模式及实例代码
2023-06-15 09:59:28 深夜i     --     --
Java 设计模式 代码案例

在Java开发中,设计模式是非常重要的一部分,它可以帮助我们提高代码的可读性、可维护性和可扩展性。在本文中,我们将介绍常用的Java设计模式,并提供实例代码进行演示。

1.单例模式

单例模式是一种只允许创建一个实例的设计模式。在Java中,定义单例模式可以使用以下代码:


public class Singleton {

  private static Singleton instance;

  private Singleton() {}

  public static Singleton getInstance() {

    if (instance == null) {

      instance = new Singleton();

    }

    return instance;

  }

}

2.工厂模式

工厂模式是一种将对象的创建过程封装起来的设计模式,通过工厂类去创建对象。在Java中,定义工厂模式可以使用以下代码:


public interface Car {

  void drive();

}

public class BMW implements Car {

  public void drive() {

    System.out.println("Driving BMW");

  }

}

public class Benz implements Car {

  public void drive() {

    System.out.println("Driving Benz");

  }

}

public class CarFactory {

  public static Car getCar(String type) {

    if (type.equalsIgnoreCase("BMW")) {

      return new BMW();

    } else if (type.equalsIgnoreCase("Benz")) {

      return new Benz();

    } else

      return null;

    

  }

}

3.观察者模式

观察者模式是一种订阅/发布模式,它允许对象在状态改变时通知其它已经订阅了该对象的对象。在Java中,定义观察者模式可以使用以下代码:


import java.util.Observable;

import java.util.Observer;

public class WeatherStation extends Observable {

  private int temperature;

  public void setTemperature(int temperature) {

    this.temperature = temperature;

    setChanged();

    notifyObservers();

  }

}

public class Phone implements Observer {

  public void update(Observable o, Object arg) {

    WeatherStation weatherStation = (WeatherStation) o;

    System.out.println("New temperature received: " + weatherStation.getTemperature());

  }

}

public static void main(String[] args) {

  WeatherStation weatherStation = new WeatherStation();

  Phone phone = new Phone();

  weatherStation.addObserver(phone);

  weatherStation.setTemperature(28);

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复