java设计模式(构建)--单例模式&抽象工厂模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chao821/article/details/87458986

一、单例模式

用途:保证一个类仅有一个实例, 并提供一个访问它的全局访问点。让类自身负责保存它的唯一实例。 这个类可以保证没有其他实例可以被创建(通过截取创建新对象的请求 ), 并且它可以提供一个访问该实例的方法。

public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
} 

二、抽象工厂模式

用途:该模式描述了怎样在不直接实例化类的情况下创建一系列相关的产品对象。 它最适用于产品对象的数目和种类不变, 而具体产品系列之间存在不同的情况。 

案例:

1、首先定义队伍中几种组成部分的接口以及实现类

public interface Member {

  String getDescription();
}

public interface Captain extends Member {

}

public interface Sailor extends Member {

}

public interface Ship extends Member {

}

2、接下来定义工厂的接口以及两种不同主题的实现类

public interface TeamFactory {

  Ship createShip();

  Captain createCaptain();

  Sailor createSailor();
}
public class YoungTeamFactory implements TeamFactory {

  public Ship createShip() {
    return new NewShip();
  }

  public Captain createCaptain() {
    return new YoungCaptain();
  }

  public Sailor createSailor() {
    return new YoungSailor();
  }
}
public class PermanentTeamFactory implements TeamFactory {

  public Ship createShip() {
    return new OldShip();
  }

  public Captain createCaptain() {
    return new OldCaptain();
  }

  public Sailor createSailor() {
    return new OldSailor();
  }
}

3、现在,创建一个团队前则需要首先创建一个工厂对象,根据不同的主题创建不同的工厂

TeamFactory factory = new YoungTeamFactory();

Ship ship = factory.createShip();
Captain = factory.createCaptain();
Sailor = factory.createSailor();

ship.getDescription();      // 崭新的船
captain.getDescription();   // 年轻的船长
sailor.getDescription();    // 年轻的水手

猜你喜欢

转载自blog.csdn.net/chao821/article/details/87458986