首页 > 开发 > 综合 > 正文

Abstract Factory pattern -- Structural example

2024-07-21 02:27:42
字体:
来源:转载
供稿:网友

uml class diagram







using system;

// "abstractfactory"

abstract class abstractfactory
{
  // methods
  abstract public abstractproducta createproducta();
  abstract public abstractproductb createproductb();
}

// "concretefactory1"

class concretefactory1 : abstractfactory
{
  // methods
  override public abstractproducta createproducta()
  {
    return new producta1();
  }
  override public abstractproductb createproductb()
  {
    return new productb1();
  }
}

// "concretefactory2"

class concretefactory2 : abstractfactory
{
  // methods
  override public abstractproducta createproducta()
  {
    return new producta2();
  }
  override public abstractproductb createproductb()
  {
    return new productb2();
  }
}

// "abstractproducta"

abstract class abstractproducta
{
}

// "abstractproductb"

abstract class abstractproductb
{
  // methods
  abstract public void interact( abstractproducta a );
}

// "producta1"


class producta1 : abstractproducta
{
}

// "productb1"

class productb1 : abstractproductb
{
  // methods
  override public void interact( abstractproducta a )
  {
    console.writeline( this + " interacts with " + a );
  }
}

// "producta2"

class producta2 : abstractproducta
{
}

// "productb2"

class productb2 : abstractproductb
{
  // methods
  override public void interact( abstractproducta a )
  {
    console.writeline( this + " interacts with " + a );
  }
}

// "client" - the interaction environment of the products

class environment
{
  // fields
  private abstractproducta abstractproducta;
  private abstractproductb abstractproductb;

  // constructors
  public environment( abstractfactory factory )
  {
    abstractproductb = factory.createproductb();
    abstractproducta = factory.createproducta();
  }
 
  // methods
  public void run()
  {
    abstractproductb.interact( abstractproducta );
  }
}

/// <summary>
///  clientapp test environment
/// </summary>

class clientapp
{
  public static void main(string[] args)
  {
    abstractfactory factory1 = new concretefactory1();
    environment e1 = new environment( factory1 );
    e1.run();

    abstractfactory factory2 = new concretefactory2();
    environment e2 = new environment( factory2 );
    e2.run();

    console.read();
  }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表