当前位置:网站首页>Block balking mode

Block balking mode

2021-05-04 14:01:23 Jiedao jdon

Purpose

Balking Pattern Used to prevent objects from executing some code in incomplete or inappropriate situations .

Wikipedia says

balking Pattern is a software design pattern , Perform operations on objects only when they are in a specific state . for example , If an object reads ZIP file , And a calling method is in zip Called when the file is not open get Method , Then the object will “ stop it ”. for example , stay Java In programming language , In these cases, it's possible to throw IllegalStateException.

Source code

In this example implementation ,WashingMachine It's an object , It has two states : Enable and clean . If the machine is enabled , The status will change to “ Cleaning in progress ”, No other thread can call and perform this operation . On the other hand , If it has been cleaned , Then any other thread can no longer execute wash() operation .

Class diagram

The first 1 Step : Create washing machine class .

package com.iluwatar.balking;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Washing machine class
 */
public class WashingMachine {

  private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class);

  private WashingMachineState washingMachineState;

  public WashingMachine() {
    washingMachineState = WashingMachineState.ENABLED;
  }

  public WashingMachineState getWashingMachineState() {
    return washingMachineState;
  }

  /**
   * Method responsible for washing
   * if the object is in appropriate state
   */
  public void wash() {
    synchronized (this) {
      LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), getWashingMachineState());
      if (washingMachineState == WashingMachineState.WASHING) {
        LOGGER.error("ERROR: Cannot wash if the machine has been already washing!");
        return;
      }
      washingMachineState = WashingMachineState.WASHING;
    }
    LOGGER.info("{}: Doing the washing", Thread.currentThread().getName());
    try {
      Thread.sleep(50);
    } catch (InterruptedException ie) {
      ie.printStackTrace();
    }
    endOfWashing();
  }

  /**
   * Method responsible of ending the washing
   * by changing machine state
   */
  public synchronized void endOfWashing() {
    washingMachineState = WashingMachineState.ENABLED;
    LOGGER.info("{}: Washing completed.", Thread.currentThread().getId());
  }

}

The first 2 Step :  establish WashingMachineState Describe the state of the machine , It can be activated and ready to work during washing .

package com.iluwatar.balking;

public enum WashingMachineState {
  ENABLED, WASHING
}

The first 3 Step : Let's test this design pattern .

public class BalkingPatternDemo {

  private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

  /**
   * @param args the command line arguments - not used
   */
  public static void main(String... args) {
    final WashingMachine washingMachine = new WashingMachine();
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    for (int i = 0; i < 3; i++) {
      executorService.execute(washingMachine::wash);
    }
    executorService.shutdown();
    try {
      executorService.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException ie) {
      LOGGER.error("ERROR: Waiting on executor service shutdown!");
    }
  }

}

Applicability

Use Balking Mode time

  • You want to call operations on an object only when it is in a specific state

  • Objects are usually only in a state that is easy to stop temporarily , But the time is uncertain .

版权声明
本文为[Jiedao jdon]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/05/20210504135746098l.html

随机推荐