Home  >  Article  >  Java  >  Introduction to the practice of design patterns in Java language

Introduction to the practice of design patterns in Java language

王林
王林Original
2023-06-11 16:09:071138browse

Introduction to the practice of design patterns in Java language

Design patterns are a proven idea and method for solving software design and development problems. They reduce complexity in software development and provide flexible, reusable code. In the Java language, the application of design patterns is extremely important. This article will introduce several commonly used design patterns in the Java language and their practical applications.

  1. Factory Pattern

Factory pattern is a design pattern for creating objects. It encapsulates the object creation process in a single class so that new instances can be easily generated when needed. The factory pattern can effectively reduce code duplication while providing greater flexibility. The following is an example of the factory pattern:

//定义接口
public interface Animal {
   void makeSound();
}

//定义实现类
public class Cat implements Animal{
   @Override
   public void makeSound() {
      System.out.println("Meow");
   }
}

public class Dog implements Animal{
   @Override
   public void makeSound() {
      System.out.println("Woof");
   }
}

public class AnimalFactory {
   public static Animal createAnimal(String animalType){
      if(animalType.equalsIgnoreCase("dog")){
         return new Dog();
      }
      else if(animalType.equalsIgnoreCase("cat")){
         return new Cat();
      }
      else return null;
   }
}

//测试
public class FactoryTest {
   public static void main(String[] args) {
      Animal myAnimal = AnimalFactory.createAnimal("dog");
      myAnimal.makeSound();
   }
}
  1. Singleton pattern

The singleton pattern is a design pattern that ensures that a class has only one instance. It is typically used to control resources and manage individual objects. The singleton pattern in Java can be implemented in lazy style or hungry style. The following is an example of a Hungry-style singleton pattern:

public class Singleton {
   private static Singleton uniqueInstance = new Singleton();
   private Singleton() {} 
   
   public static Singleton getInstance() {
      return uniqueInstance;
   }
}
  1. Observer Pattern

The Observer pattern is a pattern in which objects (called observers) By registering yourself with another object, called a topic, to receive notifications when the topic changes. The Observer pattern helps you design loosely coupled systems where objects interact with each other without causing coupling effects. Here is an example of the Observer pattern:

//定义接口
public interface Observer {
   public void update(int temperature, int humidity, int pressure);
}

//实现类
public class WeatherData implements Subject {

   private ArrayList<Observer> observers;
   private int temperature;
   private int humidity;
   private int pressure;
   
   public WeatherData(){
      observers = new ArrayList<Observer>();
   }
   
   public void registerObserver(Observer o) {
      observers.add(o);
   }

   public void removeObserver(Observer o) {
      int i = observers.indexOf(o);
      if (i >= 0) {
         observers.remove(i);
      }
   }

   public void notifyObservers() {
      for (Observer observer : observers) {
         observer.update(temperature, humidity, pressure);
      }
   }
   
   public void measurementsChanged() {
      notifyObservers();
   }
   
   public void setMeasurements(int temperature, int humidity, int pressure) {
      this.temperature = temperature;
      this.humidity = humidity;
      this.pressure = pressure;
      measurementsChanged();
   }
}

//测试
public class WeatherStation {

   public static void main(String[] args) {
      WeatherData weatherData = new WeatherData();
      CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
      weatherData.setMeasurements(80, 65, 30.4f);
      weatherData.setMeasurements(82, 70, 29.2f);
   }
}
  1. Strategy Pattern

The Strategy pattern is a pattern in which an object separates behavior into different implementations. It allows you to choose the implementation of your algorithm at runtime, providing greater flexibility. Strategy pattern helps you design reusable code while reducing duplication.

//定义接口
public interface FlyBehavior {
   public void fly();
}

public class FlyWithWings implements FlyBehavior {
   public void fly() {
      System.out.println("I'm flying!!");
   }
}

public interface QuackBehavior {
   public void quack();
}

public class Quack implements QuackBehavior {
   public void quack() {
      System.out.println("Quack");
   }
}

//策略模式实现类
public abstract class Duck {
   FlyBehavior flyBehavior;
   QuackBehavior quackBehavior;

   public void performFly() {
      flyBehavior.fly();
   }

   public void performQuack() {
      quackBehavior.quack();
   }

   public void setFlyBehavior(FlyBehavior fb) {
      flyBehavior = fb;
   }

   public void setQuackBehavior(QuackBehavior qb) {
      quackBehavior = qb;
   }
}

public class MallardDuck extends Duck {
   public MallardDuck() {
      quackBehavior = new Quack();
      flyBehavior = new FlyWithWings();
   }

   public void display() {
      System.out.println("I'm a real Mallard duck");
   }
}

//测试
public class MiniDuckSimulator {
 
    public static void main(String[] args) {
 
        Duck mallard = new MallardDuck();
        mallard.performQuack();
        mallard.performFly();
    }
}

Summary:

Design patterns are very useful programming ideas and methods in the Java language. Factory pattern, singleton pattern, observer pattern and strategy pattern are all commonly used design patterns, and their practical application can greatly improve the flexibility and reusability of the program. We hope that the content of design patterns described in this article will be helpful to readers in deepening their understanding and practical application of design patterns.

The above is the detailed content of Introduction to the practice of design patterns in Java language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn