Ejemplo de como quitar un switch y sustituirlo por una factoria:
public
void
ProcessCustomer(CustomerMessage message)
{
switch
(message.CustomerCategory)
{
case
Category.Gold:
ProcessGoldCustomer(message);
break
;
case
Category.Silver:
ProcessSilverCustomer(message);
break
;
case
Category.Bronze:
ProcessBronzeCustomer(message);
break
;
}
}
Ejemplo con factoría:
public
interface
ICustomerProcessor
{
void
Process(CustomerMessage message);
}
public
class
GoldCustomerProcessor : ICustomerProcessor {...}
public
class
SilverCustomerProcessor : ICustomerProcessor {...}
public
class
BronzeCustomerProcessor : ICustomerProcessor {...}
public
class
CustomerProcessorFactory
{
public
ICustomerProcessor Create(Category category) {
switch (category) {
case
Category.Gold:
return new
GoldCustomerProcessor();
}
...
}
}
public
void
ProcessCustomer(CustomerMessage message)
{
var
factory =
new
CustomerProcessorFactory();
var
processor = factory.Create(message.CustomerCategory);
processor.Process(message);
}
Ejemplo patrón Tester/Doer:
public
interface
ICustomerProcessor
{
bool
CanProcess(CustomerMessage message);
void
Process(CustomerMessage message);
}
public
class
GoldCustomerProcessor : ICustomerProcessor
{
public
bool
CanProcess(CustomerMessage message)
{
return
message.CustomerCategory == Category.Gold;
}
public
void
Process(CustomerMessage message) {...}
}
public
class
SilverCustomerProcessor : ICustomerProcessor {...}
public
class
BronzeCustomerProcessor : ICustomerProcessor {...}
public
void
ProcessCustomer(CustomerMessage message)
{
var
processor =
this
.processors.Single(x => x.CanProcess(message));
processor.Process(message);
}
No hay comentarios:
Publicar un comentario