[设计模式]简单工厂模式(Simple Factory)

帅比萌擦擦* 提交于 2019-11-27 04:42:46

 

ContractedBlock.gifExpandedBlockStart.gifCode
using System;
using System.Collections.Generic;
using System.Text;

namespace Learning.DesignPattern
ExpandedBlockStart.gifContractedBlock.gif
{
    
//简单工厂模式(Simple Factory)

    
//产品接口ICar
    public interface ICar
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
void Drive();
    }


    
//具体的产品类实现ICar接口
    public class HongQi : ICar
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
public void Drive()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Console.WriteLine(
"The driver driving the HongQi!");
        }

    }


    
public class DaZhong : ICar
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
public void Drive()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Console.WriteLine(
"The driver driving the DaZhong!");
        }

    }



    
//工厂类:
    public class CarFactory
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
public static ICar DriveCar(string carName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (carName == "HongQi")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return new HongQi();
            }

            
else if (carName == "DaZhong")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return new DaZhong();
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return null;
            }

        }

    }



    
//调用该工厂类,执行具体产品方法:
    public class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
public static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
string carName = "HongQi";
            Console.Write(
"请输入车名:");
            Console.Write(
"+>");
            carName 
= Console.ReadLine();
            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                CarFactory.DriveCar(carName).Drive();
            }

            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Console.Write(
"您输入的车名无效!");
            }

            Console.ReadLine();
        }

    }

}

转载于:https://www.cnblogs.com/xinerzhui/archive/2008/10/14/1311145.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!