Hey everyone,
I’m learning mostly used design patterns for game development. I made an example about the flyweight pattern. Did I implement pattern correctly?
There is 2 different block that names are A and B. As a variable name, height and width are same some objects but point is different for every blocks.
Thanks for help ![]()
// Block.cs
namespace Oyun_Programalama_Tasarım_Desenleri
{
public abstract class Block
{
protected string name;
protected int height;
protected int width;
protected string point; // different for every blocks.
public abstract void Display(string point);
}
}
// BlockA.cs
namespace Oyun_Programalama_Tasarım_Desenleri
{
public class BlockA : Block
{
public BlockA()
{
name = "A";
height = 16;
width = 16;
}
public override void Display(string point)
{
// point is different for every block
this.point = point;
Console.WriteLine(name + " " + height + " " + width + " " + this.point);
}
}
}
// BlockB.cs
namespace Oyun_Programalama_Tasarım_Desenleri
{
public class BlockB : Block
{
public BlockB()
{
name = "B";
height = 16;
width = 16;
}
public override void Display(string point)
{
// point is different for every block
this.point = point;
Console.WriteLine(name + " " + height + " " + width + " " + this.point);
}
}
}
// BlockFactory.cs
namespace Oyun_Programalama_Tasarım_Desenleri
{
public class BlockFactory
{
private Dictionary<char, Block> blocks = new Dictionary<char, Block>();
public Block GetBlock(char key)
{
Block block = null;
if (blocks.ContainsKey(key))
{
block = blocks[key];
}
else
{
switch (key)
{
case 'A': block = new BlockA(); break;
case 'B': block = new BlockB(); break;
}
blocks.Add(key, block);
}
return block;
}
}
}
// Program.cs
namespace Oyun_Programalama_Tasarım_Desenleri
{
class Program
{
static void Main(string[] args)
{
char key;
BlockFactory blockFactory = new BlockFactory();
Block blockA = blockFactory.GetBlock('A');
blockA.Display("1");
Block blockB = blockFactory.GetBlock('B');
blockB.Display("2");
Console.ReadKey();
}
}
}