C#简单抽象工厂

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            AbstractFactory abstractFactory = AbstractFactory.Factory("samsang");
            IMP4 iMP4 = abstractFactory.CreateMP4();
            iMP4.Look();
        }
    }

    //抽象工厂
    public abstract class AbstractFactory
    {
        public static  AbstractFactory Factory(string type)
        {
            AbstractFactory factory=null;
            switch(type)
            {
                case "sony":
                    factory=new SonyFactory();
                    break;
                case "samsang":
                    factory=new SamsanyFactory();
                    break;
            }
            return factory;
         }
        //通过抽象产品,创建实际产品
        public abstract IMP3 CreateMP3();
        public abstract IMP4 CreateMP4();
    }

    //索尼的实际工厂
    public class SonyFactory:AbstractFactory
    {
        public override IMP3  CreateMP3()
        {
 	        return new SonyMP3();
        }
        public override IMP4  CreateMP4()
        {
 	        return new SonyMP4();
        }
    }

    //三星的实际工厂
    public class SamsanyFactory:AbstractFactory
    {
        public override IMP3  CreateMP3()
        {
 	        return new SamsangMP3();
        }
        public override IMP4  CreateMP4()
        {
 	        return new SamsangMP4();
        }
    }

    //MP3的抽象产品
    public interface IMP3
    {
        void Listen();
    }

    //MP4的抽象产品
    public interface IMP4
    {
        void Listen();
        void Look();
    }

    //MP3的实际产品(索尼的)
    public class SonyMP3 : IMP3
    {
        public void Listen()
        {
            Console.WriteLine("索尼 MP3 可以听");
        }
    }

    //MP3的实际产品(三星的)
    public class SamsangMP3 : IMP3
    {
        public void Listen()
        {
            Console.WriteLine("三星 MP3 可以听");
        }
    }

    //MP4的实际产品(索尼的)
    public class SonyMP4 : IMP4
    {
        public void Listen()
        {
            Console.WriteLine("索尼 MP4 可以听");
        }
        public void Look()
        {
            Console.WriteLine("索尼 MP4 可以看");
        }
    }

    //MP4的实际产品(三星的)
    public class SamsangMP4 : IMP4
    {
        public void Listen()
        {
            Console.WriteLine("三星 MP4 可以听");
        }
        public void Look()
        {
            Console.WriteLine("三星 MP4 可以看");
        }
    }
}

你可能感兴趣的:(C#简单抽象工厂)