21xrx.com
2024-09-19 08:15:38 Thursday
登录
文章检索 我的文章 写文章
《Java设计模式的作用》
2023-06-12 16:40:31 深夜i     --     --
Java设计模式 工厂模式 单例模式 观察者模式

Java是一种面向对象的编程语言,随着程序规模的不断扩大,面向对象的设计思想变得越来越重要。而设计模式,就是针对一些常见的问题或需求所提出的解决方案,可以帮助开发者更好地设计程序结构和逻辑。在本文中,将介绍Java中常用的几种设计模式及其作用。

一、工厂模式

工厂模式是一种创建对象的方式,将对象的创建过程放到一个专门的类中。这样做的好处是可以将对象创建的细节和使用者隔离开来,提高代码的可维护性和可读性。

代码示例:


interface Car {

  void run();

}

class Benz implements Car {

  public void run() {

   System.out.println("Benz is running");

  }

}

class CarFactory {

  public Car createCar(String type) {

   if (type.equals("Benz")) {

     return new Benz();

   }

   return null;

  }

}

public class FactoryDemo {

  public static void main(String[] args) {

   CarFactory factory = new CarFactory();

   Car car = factory.createCar("Benz");

   car.run();

  }

}

二、单例模式

单例模式是一种保证只有一个实例对象存在的设计模式。在Java中,可以通过私有构造方法和静态方法来实现。

代码示例:


class Singleton {

  private static Singleton instance = null;

  private Singleton() {}

  public static synchronized Singleton getInstance() {

   if (instance == null) {

     instance = new Singleton();

   }

   return instance;

  }

}

public class SingletonDemo {

  public static void main(String[] args) {

   Singleton s1 = Singleton.getInstance();

   Singleton s2 = Singleton.getInstance();

   System.out.println(s1 == s2);

  }

}

三、观察者模式

观察者模式是一种将对象间的依赖关系分离出来的设计模式。在这种模式中,一个对象(也称为主题)会通知一组依赖它的对象(也称为观察者)状态的变化。这样,当主题的状态发生改变时,所有的观察者都会得到通知并进行相应的处理。

代码示例:


import java.util.Observable;

import java.util.Observer;

class WeatherData extends Observable {

  private float temperature;

  public void setTemperature(float temp) {

   this.temperature = temp;

   setChanged();

   notifyObservers();

  }

  public float getTemperature()

   return temperature;

 

}

class CurrentConditionsDisplay implements Observer {

  private Observable observable;

  public CurrentConditionsDisplay(Observable o) {

   this.observable = o;

   observable.addObserver(this);

  }

  public void update(Observable o, Object arg) {

   if (o instanceof WeatherData) {

     WeatherData weatherData = (WeatherData)o;

     float temperature = weatherData.getTemperature();

     System.out.println("Current temperature is " + temperature);

   }

  }

}

public class ObserverDemo {

  public static void main(String[] args) {

   WeatherData weatherData = new WeatherData();

   CurrentConditionsDisplay conditionsDisplay = new CurrentConditionsDisplay(weatherData);

   weatherData.setTemperature(25);

  }

}

三个

  
  

评论区

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