把创建对象的事情 封装起来
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPytternDemo
{
/// <summary>
/// 简单工厂
/// </summary>
public interface IFood
{
int Price { get; }
}
public class Orange : IFood
{
public Orange()
{
Console.WriteLine("orange created");
}
public int Price
{
get
{
return 1;
}
}
}
public class Rice : IFood
{
public Rice()
{
Console.WriteLine("rice created");
}
public int Price
{
get
{
return 3;
}
}
}
public static class FoodFactory
{
public static IFood CreateFood(string foodType)
{
IFood f = null;
switch (foodType)
{
case "o":
f = new Orange();
break;
case "r":
f = new Rice();
break;
default:
break;
}
return f;
}
}
/// <summary>
/// 抽象工厂
/// </summary>
public interface IActionGame
{
}
public class Kof : IActionGame
{
public Kof()
{
Console.WriteLine("Kof created");
}
}
public class War3 : IActionGame
{
public War3()
{
Console.WriteLine("War3 created");
}
}
public class Cs : IActionGame
{
public Cs()
{
Console.WriteLine("Cs created");
}
}
public interface IRPG
{
}
public class menghuan : IRPG
{
public menghuan()
{
Console.WriteLine("menghuan created");
}
}
public class Legend : IRPG
{
public Legend()
{
Console.WriteLine("Legend created");
}
}
public class Diablo : IRPG
{
public Diablo()
{
Console.WriteLine("Diablo created");
}
}
public abstract class GameFactory
{
public abstract IActionGame CreateActionGame();
public abstract IRPG CreateRpgGame();
}
public class MyGameFactory : GameFactory
{
public override IActionGame CreateActionGame()
{
return new Kof();
}
public override IRPG CreateRpgGame()
{
return new Legend();
}
}
} 以上就是C# 设计模式之 工厂模式的内容,更多相关内容请关注PHP中文网(www.php.cn)!
系统介绍 45°C 商城系统,以 Thinkphp5.0 + Uniapp + Layui2.9 + Vue 为技术基石,精心打造出的全新 MINI 商城应用。其功能覆盖全面,无论是 PC 商城、H5 商城,还是公众号商城、微信小程序以及抖音小程序的制作都能完美胜任。采用标准系统结合插件模式开发,用户能够极为便捷地定制专属的个性模块。整个系统,从程序设计到 UI 呈现,都秉持着一贯的小而美理念。程
0
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号