首页 > 开发 > 综合 > 正文

C#设计模式之抽象工厂(abstract factory)模式示例源代码

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

using system;

namespace design_pattern
{

 public class  computer
 {
  private ram ram;
  private cpu cpu;
  public computer(ram ram,cpu cpu)
  {
   this.ram =ram;
   this.cpu =cpu;
   
   console .writeline("a computer is composed! "+this.ram +" "+this.cpu );
  }
 }

 public abstract class ram
 {
  public abstract  computer composeacomputer(cpu cpu);
 }
 public abstract class cpu
 {
 public abstract  computer composeacomputer(ram ram);
 }
 



 public class pcram:ram
 {
  public override computer composeacomputer(cpu cpu)
  {
   console .writeline ("pccomputer...");

   return new computer(this,cpu);
  }

  
 }

 public class pccpu:cpu
 {
  public override computer composeacomputer(ram ram)
  {
   console .writeline ("pccomputer...");

   return new computer(ram,this);
  }

 }


 public class macram:ram
 {
  public override computer composeacomputer(cpu cpu)
  {
   console .writeline ("maccomputer...");
   return new computer(this,cpu);
  }

  
 }

 public class maccpu:cpu
 {
  public override computer composeacomputer(ram ram)
  {
   console .writeline ("maccomputer...");
   return new computer(ram,this);
  }

 }
 
 public abstract class abstractfactory
{
       public abstract  ram createram();
   public abstract cpu createcpu() ;
}

 public class pcfactory:abstractfactory
 {
  public override ram createram()
  {
   return new pcram();
  }
  public override cpu createcpu()
  {
   return new pccpu();
  }

 }


 public class macfactory:abstractfactory
 {
  public override ram createram()
  {
   return new macram();

  }
  public override cpu createcpu()
  {
   return new maccpu();
  }


 }

 class itmarket
 {
  private ram ram;
  private cpu cpu;
  public itmarket(abstractfactory factory)
  {
   this.ram =factory.createram();
   this.cpu =factory.createcpu();
  }
  public void run()
  {
   ram.composeacomputer(cpu);
   cpu.composeacomputer(ram);
  }

 }

 class clientapp
 {
  public static void main(string[] args)
  {
   console .writeline("pc factory...../n");
   abstractfactory pcfactory=new pcfactory ();
   itmarket itmarket=new itmarket (pcfactory);
   itmarket .run ();

   console .writeline("mac factory...../n");
   abstractfactory macfactory=new macfactory();
   itmarket =new itmarket (macfactory);
   itmarket .run ();
  }
 }

   

}

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