简单工厂模式:
using System;
namespace CSharpDesignPattern.Factory
{
public enum EnemyType
{
AirPlane = 0,
Tank = 1,
}
public class SimpleFactory
{
private int screenWidth;
private Random random;
public SimpleFactory(int screenWidth)
{
this.screenWidth = screenWidth;
this.random = new Random();
}
public Enemy Create(EnemyType type)
{
int x = random.Next(screenWidth);
Enemy enemy = null;
switch (type)
{
case EnemyType.AirPlane:
enemy = new AirPlane(x, 0);
break;
case EnemyType.Tank:
enemy = new Tank(x, 0);
break;
}
return enemy;
}
}
}
通过接口实现各自的工厂模式
namespace CSharpDesignPattern.Factory
{
public interface IFactory
{
Enemy Create(int screenWidth);
}
public class TankFactory : IFactory
{
public Enemy Create(int screenWidth)
{
Random rnd = new Random();
return new Tank(rnd.Next(screenWidth), 0);
}
}
public class AirplaneFactory : IFactory
{
public Enemy Create(int screenWidth)
{
Random rnd = new Random();
return new AirPlane(rnd.Next(screenWidth), 0);
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。