using System;
using
System.Collections.Generic;
namespace
FlyweightSample
{
/// <summary>
/// EN: Uses the
pattern flyweight to
/// extreme reuse
virtual memory, this sample
/// shows how to use
this patterns with the
/// most comom
situation, how to load the
/// users permissions
reusing when the same
/// roles are used
for many users.
///
/// PT: Utilize o
padrão flyweight para
/// um reuso extremo
de memoria virtual
/// este exemplo
mostra como utilizar este
/// padrão em uma das
mais comuns situações,
/// como carregar as
permissões dos usuários
/// reusando-as
quando as mesmas forem utilizadas
/// por varios usuários.
/// </summary>
public class SaleSample
internal class Program
{
private static void Main(string[]
args)
{
//EN: Here we just get permissions,
//many users will use this routine
//everyday
//PT: Aqui fazemos simplesmente fazendo
//um get das permissões, varios usuários
//passaram por esta rotina diariamente
FlyweightRoleFactory factory = new FlyweightRoleFactory();
FlyweightRole myRole = factory.GetRole(1);
}
}
/// <summary>
/// EN: Here we
create the roles abstraction that
/// can be used for a
lot of systems
///
/// PT: Aqui criamos
a abstração de roles que pode ser
/// utilizado por
varios sitemas
/// </summary>
public abstract
class FlyweightRole
{
public int
RoleId { get; set;
}
public string
RoleName { get; set;
}
public abstract
int PermissionLevel { get;
set; }
}
public class SystemARole : FlyweightRole
{
public int
minLevel = 1;
public int
maxLevel = 5;
public int
permissionLevel = 1;
public override
int PermissionLevel
{
get { return
permissionLevel; }
set
{
if (value <
minLevel)
{
throw new Exception("Min
value for this property is "
+ minLevel.ToString());
}
if (value >
maxLevel)
{
throw new
Exception("Max
value for this property is "
+ maxLevel.ToString());
}
permissionLevel = value;
}
}
}
public class SystemBRole : FlyweightRole
{
public int
minLevel = 0;
public int
maxLevel = 8;
public int
permissionLevel = 0;
public override
int PermissionLevel
{
get { return
permissionLevel; }
set
{
if (value <
minLevel)
{
throw new Exception("Min
value for this property is "
+ minLevel.ToString());
}
if (value >
maxLevel)
{
throw new
Exception("Max
value for this property is "
+ maxLevel.ToString());
}
permissionLevel = value;
}
}
}
/// <summary>
/// EN: Here the
trick happens, we create the roles only if it
/// doesn't exists on
virtual memory, if exists, we just return
/// the role
reference, this class works with Web systems, for
/// client-server
systems, you should create a shared dll or
/// WCF Service.
///
/// PT: Aqui o truque
acontece, criamos as roles somente se elas não
/// existirem na memória,
caso contrario retornamos uma referencia
/// sua, esta classe
funcionaria legal em um sistema web, em um
/// sistema
client-server, para termos o mesmo efeito, precisariamos
/// coloca-la em uma
dll compartilhada por varios sistemas, ou
/// simplesmente
criar um serviço WCF.
/// </summary>
public class FlyweightRoleFactory
{
private Dictionary<int, FlyweightRole>
loadedRoles =
new Dictionary<int, FlyweightRole>();
public FlyweightRole
GetRole(int roleId)
{
if (loadedRoles.ContainsKey(roleId))
{
return loadedRoles[roleId];
}
switch (roleId)
{
case 0:
{
loadedRoles.Add(0,FakeDataBase.GetAdmRoleA());
break;
}
case 1:
{
loadedRoles.Add(0,FakeDataBase.GetPublicRoleA());
break;
}
case 2:
{
loadedRoles.Add(2,FakeDataBase.GetAdmRoleB());
break;
}
case 3:
{
loadedRoles.Add(3,FakeDataBase.GetPublicRoleB());
break;
}
default:
{
throw new Exception("Invalid
RoleId.");
}
}
return loadedRoles[roleId];
}
}
public class FakeDataBase
{
public static FlyweightRole GetAdmRoleA() {
return new SystemARole()
{
RoleId = 0,
RoleName = "Administrator",
PermissionLevel = 5
};
}
public static FlyweightRole GetPublicRoleA() {
return new SystemARole()
{
RoleId = 1,
RoleName = "Public",
PermissionLevel = 1
};
}
public static FlyweightRole GetAdmRoleB() {
return new SystemARole()
{
RoleId = 2,
RoleName = "Administrator",
PermissionLevel = 8
};
}
public static FlyweightRole GetPublicRoleB() {
return new SystemARole()
{
RoleId = 3,
RoleName = "Public",
PermissionLevel = 0
};
}
}
}