首页 > 其他 > 详细

工厂方法

时间:2018-06-27 17:12:59      阅读:189      评论:0      收藏:0      [点我收藏+]

1.简介

  相比于简单工厂,工厂方法是使用一个工厂类去创建一个对象

  IRace接口和Human类都和上文简单工厂一样

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethod
{
    public interface IRace
    {
        void ShowKing();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethod
{
    class Human : IRace
    {
        public void ShowKing()
        {
            Console.WriteLine("这里是人类的国王");
        }
    }
}

  然后我们添加一个Human工厂HumanFactory,用这个类来实例化Human

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethod
{
    public class HumanFactory
    {
        public IRace CreateInstance()
        {
            return new Human();
        }
    }
}

  Program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            HumanFactory humanFactory = new HumanFactory();
            IRace race1 = humanFactory.CreateInstance();
            race1.ShowKing();
            Console.Read();
        }
    }
}

  从这里看,我们可能会觉得工厂方法只是   

 

工厂方法

原文:https://www.cnblogs.com/wskxy/p/9234878.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!