创建型模式
创建型模式对类的实例化进行了抽象,能够使软件模块做到与对象的创建和组织无关。创建型模式隐藏了对象是如何被创建的和组合在一起的,以达到使整个系统独立的目的。
工厂模式
工厂模式又称虚拟构造机模式或者多态模式,属于类的创建模式。在工厂方法模式中,父类负责定义创建对象的公共接口,而子类则负责生成具体的对象,这样做的目的是将类的实例化操作延迟到子类中完成,由子类来决定究竟要创建哪一个类。
// Copyright(C) 2000-2003 Yoshinori Oota All rights reserved.
public class FactoryMethodSample
{
static public Creator Create(String str)
{
if (str.equals("A"))
{
return new CreatorA();
}
else if (str.equals("B"))
{
return new CreatorB();
}
return null;
}
static public void main(String[] args)
{
Creator creator1 = Create("A"); // クライアントコードは、ConcreteCreatorが、
Creator creator2 = Create("B"); // AかBか、意識する必要はない
Product product1 = creator1.FactoryMethod();
Product product2 = creator2.FactoryMethod();
product1.Operation();
product2.Operation();
}
}
// abstract class to be implemented by CreatorA and CreatorB
abstract class Creator
{
// only method to be implemented by subclass
abstract public Product FactoryMethod();
}
class CreatorA extends Creator
{
public Product FactoryMethod()
{
return new ProductA(); // an instance of ProductA is created
}
}
class CreatorB extends Creator
{
public Product FactoryMethod()
{
return new ProductB(); // an instance of ProductB is created
}
}
abstract class Product
{
abstract void Operation();
}
class ProductA extends Product
{
public void Operation()
{
System.out.println("ProductA");
}
}
class ProductB extends Product
{
public void Operation()
{
System.out.println("ProductB");
}
}
抽象工厂模式
抽象工厂模式又称Kit模式。抽象工厂模式是所有形式的工厂模式中最为抽象和最具一般性的一种形态,它提供了一个创建一系列相关或互相依赖对象的接口,而无需指定它们具体的类。在抽象工厂模式中,引入了产品等级结构和产品族的概念,产品等级结构是指抽象产品与具体产品构成的继承层次关系,产品族是同一个工厂所生产的一系列产品,即位于不同产品等级结构且功能相关联的产品组成的家族。当抽象工厂模式只有一个产品等级结构时,即变成了工厂方法模式。
// Copyright(C) 2000-2003 Yoshinori Oota All rights reserved.
public class AbstractFactorySample
{
static AbstractFactory Create(String sw)
{
if (sw.equals("A"))
{
return new AbstractFactoryA();
}
else if (sw.equals("B"))
{
return new AbstractFactoryB();
}
return null;
}
static public void main(String[] args)
{
// create factory a by using a method
AbstractFactory factory = Create("A");
// create product a and product b
ProductA a = factory.CreateProductA();
ProductB b = factory.CreateProductB();
// what the two products will do?
a.Operation();
b.Operation();
// create factory b by using a method
factory = Create("B");
// create product a and product b
a = factory.CreateProductA();
b = factory.CreateProductB();
// what the two products will do?
a.Operation();
b.Operation();
}
}
// abstract class
abstract class AbstractFactory
{
abstract public ProductA CreateProductA();
abstract public ProductB CreateProductB();
}
// concrete class
class AbstractFactoryA extends AbstractFactory
{
public ProductA CreateProductA()
{
return new ProductA1();
}
public ProductB CreateProductB()
{
return new ProductB1();
}
}
// concrete class
class AbstractFactoryB extends AbstractFactory
{
public ProductA CreateProductA()
{
return new ProductA2();
}
public ProductB CreateProductB()
{
return new ProductB2();
}
}
// abstract class
abstract class ProductA
{
abstract void Operation();
}
// abstract class
abstract class ProductB
{
abstract void Operation();
}
// concrete class
class ProductA1 extends ProductA
{
public void Operation()
{
System.out.println("ProductA1");
}
}
// concrete class
class ProductB1 extends ProductB
{
public void Operation()
{
System.out.println("ProductB1");
}
}
// concrete class
class ProductA2 extends ProductA
{
public void Operation()
{
System.out.println("ProductA2");
}
}
// concrete class
class ProductB2 extends ProductB
{
public void Operation()
{
System.out.println("ProductB2");
}
}
原型模式
原型方法模式通过给出一个原型对象来指明要创建的对象的类型,然后通过复制这个原型对象的,创建出更多同类型的对象。原型模式是一种对象创建型模式,用原型实例指定创建对象的种类,并通过复制这些原型创建新的对象
// Copyright(C) 2000-2003 Yoshinori Oota All rights reserved.
public class PrototypeSample {
static Prototype Create(char sw) {
if (sw == 'A') {
return new PrototypeA();
} else if (sw == 'B') {
return new PrototypeB();
}
return null;
}
static public void main(String[] args) {
Prototype prototype = Create('A');
prototype.Operation("Hello"); // 値を変えてみる
Prototype clone = prototype.Clone();
clone.Operation(); // 属性が引き継がれました。
prototype = Create('B');
prototype.Operation("1234");
clone = prototype.Clone();
clone.Operation();
}
}
abstract class Prototype {
abstract public Prototype Clone();
abstract public void Operation(String str);
abstract public void Operation();
}
class PrototypeA extends Prototype {
private String _value = "";
public PrototypeA(){}
public PrototypeA(PrototypeA p) {
_value = p._value;
}
public void Operation(String str) {
_value = str;
System.out.println("update PrototypeA::_value to " + _value);
}
public void Operation() {
System.out.println("PrototypeA::_value is " + _value);
}
public Prototype Clone() {
return new PrototypeA(this);
}
}
class PrototypeB extends Prototype {
private Integer _value = new Integer(-1);
public PrototypeB(){}
public PrototypeB(PrototypeB p) {
_value = p._value;
}
public void Operation(String str) {
_value = Integer.decode(str);
System.out.println("update PrototypeB::_value to " + _value);
}
public void Operation() {
System.out.println("PrototypeB::_value is " + _value);
}
public Prototype Clone() {
return new PrototypeB(this);
}
}
单例模式
单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,提供全局访问的方法。
// Copyright(C) 2000-2003 Yoshinori Oota All rights reserved.
public class SingletonSample
{
static public void main(String[] args)
{
Singleton theSingleton = Singleton.Instance();
theSingleton.printState();
theSingleton.nextState();
theSingleton.printState();
//try to use Singleton.Instance() to get another singleton instance
Singleton anotherSingleton = Singleton.Instance();
// now print the state to see if we really got a different instance
anotherSingleton.printState();
theSingleton.printState();
// let anotherSingleton call nextState(), and see if there is any
// difference with the state of theSingleton
anotherSingleton.nextState();
anotherSingleton.printState();
theSingleton.printState();
// Singleton singleton2 = new Singleton(); // see what will happen
} // you got an compilation error
}
class Singleton
{
private String _state = "initial state";
private static Singleton _instance = null;
private Singleton() { }
public static Singleton Instance()
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
public void printState()
{
System.out.println(_state);
}
public void nextState()
{
if (_state.compareTo("initial state") == 0)
{
_state = "second state";
}
else if (_state.compareTo("second state") == 0)
{
_state = "third state";
}
else if (_state.compareTo("third state") == 0)
{
_state = "initial state";
}
}
}
建造者模式
建造者模式强调将一个复杂对象的构建与它的表示分类,使得同样的构建过程可以创建不同的表示。建造者模式是一步一步的创建一个复杂的对象。它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。
// Copyright(C) 2000-2003 Yoshinori Oota All rights reserved.
import java.util.*;
public class BuilderSample {
static public void main(String[] args) {
Director director = new Director();
Builder builder = new Builder();
director.Construct(builder);
Component tree = builder.GetResult();
tree.print(0);
}
}
class Director {
public void Construct(Builder builder) {
// 次のような Composite構造を生成する
// Composite("Root") -+- Leaf("L1")
// +- Leaf("L2")
// +- Composite("A") -+-Leaf("L3")
// +-Leaf("L4")
builder.BuildLeaf("L1");
builder.BuildLeaf("L2");
builder.BuildComposite("A");
builder.ChangeCurrent("A");
builder.BuildLeaf("L3");
builder.BuildLeaf("L4");
}
}
class Builder {
private Composite _root = new Composite("Root");
private Composite _curComposite = _root;
public void BuildLeaf(String id) {
_curComposite.add(new Leaf(id));
}
public void BuildComposite(String id) {
_curComposite.add(new Composite(id));
}
public void ChangeCurrent(String id) {
_curComposite = (Composite)_curComposite.getComponentById(id);
}
public Component GetResult() {
return _root;
}
}
abstract class Component {
private String _name = null;
public Component(String id) {
_name = id;
}
public String getName() {
return _name;
}
protected void indent(int ind) {
for (int i = 0; i < ind; ++i) {
System.out.print(" ");
}
}
abstract public void print(int n);
}
class Leaf extends Component {
public Leaf(String id) {
super(id);
}
public void print(int n) {
indent(n);
System.out.println("- Leaf(" + getName() +")");
}
}
class Composite extends Component {
private HashMap _children = new HashMap();
public Composite(String id) {
super(id);
}
public void add(Component component) {
_children.put(component.getName(), component);
}
public Component getComponentById(String id) {
return (Component)_children.get(id);
}
public void print(int n) {
indent(n);
System.out.println("+ Composite(" + getName() +")");
Set keySet = _children.keySet();
Iterator it = keySet.iterator();
while (it.hasNext()) {
String name = (String)it.next();
Component c = (Component)_children.get(name);
++n;
c.print(n);
--n;
}
}
}