java 单身设计模式示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 单身设计模式示例相关的知识,希望对你有一定的参考价值。

package com.art.head_first.chocolateboiler;


import org.junit.Test;

public class ChocolateBoilerTest {

  @Test
  public void testChocolateBoiler(){
    ChocolateBoiler chocolateBoiler = ChocolateBoiler.getInstance();

    chocolateBoiler.fill();
    chocolateBoiler.boil();
    chocolateBoiler.drain();

  }
}
package com.art.head_first.chocolateboiler;

class ChocolateBoiler {

  private static ChocolateBoiler uniqueInstance;

  private boolean empty;
  private boolean boiled;

  private ChocolateBoiler() {
    empty = true;
    boiled = false;
  }

  /*
  Static Singleton Method
  By Adding the synchronized keyword to getInstance(), we force every thread to wait its turn
  before it can enter the method. That is no two threads may enter the method at the same time.
   */
  static synchronized ChocolateBoiler getInstance(){
    if (uniqueInstance == null){
      uniqueInstance = new ChocolateBoiler();
    }
    return uniqueInstance;
  }

  void fill(){
    if (empty){
      empty = false;
      boiled = false;
      System.out.println("Filling News Chocolates");
    }
  }

  void boil(){
    if (!empty && !boiled){
      boiled = true;
      System.out.println("Boiling Chocolates");
    }
  }

  void drain(){
    if (!empty && boiled){
      empty = true;
      System.out.println("Draining Chocolates");
    }
  }
}

以上是关于java 单身设计模式示例的主要内容,如果未能解决你的问题,请参考以下文章

java 单身模式

工厂模式--摆脱你日复一日new对象却依旧单身的苦恼!

工厂模式--摆脱你日复一日new对象却依旧单身的苦恼!

phpwamp单身狗模式的详解与分析,单身狗模式/即霸体模式的作用讲解。

phpwamp单身狗模式的详解与分析,单身狗模式/即霸体模式的作用讲解。

java 设计模式之过滤器模式(Filter)