今天百无聊赖的成果

照着UML图,随便写了个Abstract Factory模式



Load assembly的时候有点不一样,因为那个目录很怪很长,是个临时目录,所以我用location得到了它。很奇怪阿。怎么放那里,看来vs2008是不一样阿。

 string location = Assembly.GetAssembly(Type.GetType(factoryName)).Location; 
 factory = (IFactory)Assembly.LoadFile(location).CreateInstance(factoryName);

代码没啥说的,就是连连手而已。小时候看图说话,现在看图写代码,哈哈。

using System;
using System.Collections;
using System.Configuration;
using System.Reflection;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class FactoryMethod : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string factoryName = ConfigurationManager.AppSettings.Get("factoryName");
        string location = Assembly.GetAssembly(Type.GetType(factoryName)).Location;

        IFactory factory;
        factory = (IFactory)Assembly.LoadFile(location).CreateInstance(factoryName);

        Response.Write(factory.CreateProduct1());
        Response.Write(factory.CreateProduct2());
    }
}


//interface for productA
public interface IProduct1
{
    string GetProductName();
}

//interface for productB
public interface IProduct2
{
    string GetProductCode();
}

public class ProductA1 : IProduct1
{
    public string GetProductName()
    {
        return "ProductA1";
    }
}

public class ProductA2 : IProduct2
{
    public string GetProductCode()
    {
        return "ProductA2";
    }
}

public class ProductB1 : IProduct1
{
    public string GetProductName()
    {
        return "ProductB1";
    }
}

public class ProductB2 : IProduct2
{
    public string GetProductCode()
    {
        return "ProductB2";
    }
}

interface IFactory
{
    IProduct1 CreateProduct1();
    IProduct2 CreateProduct2();
}

public class FactoryA : IFactory
{
    public IProduct1 CreateProduct1()
    {
        return new ProductA1();
    }

    public IProduct2 CreateProduct2()
    {
        return new ProductA2();
    }
}

public class FactoryB : IFactory
{
    public IProduct1 CreateProduct1()
    {
        return new ProductB1();
    }

    public IProduct2 CreateProduct2()
    {
        return new ProductB2();
    }
}


 

posted @ 2008-02-13 17:39  helloworld22  阅读(458)  评论(2编辑  收藏  举报