I have the following classes.
public class Container
{
private ResourceA a;
private ResourceB b;
private List<User> users;
public void handleUser(User u)
{
if (u is UserA ua)//cast into userA
{
ua.useResourceA(a);
}else if (u is UserB ub)
{
ub.useResourceB(b);
}
}
}
public class User
{
}
public class UserA: User
{
public void useResourceA(ResourceA a)
{
//do something with a
}
}
public class UserB: User
{
public void useResourceB(ResourceB b)
{
//do something with b
}
}
ResourceA and B behave very differently. It's not possible to have a base class for the two of them. Yet UserA and UserB share some functionality and I need a list containing resource users for various reasons. I then also need to handle resource grant requests from the base class. So I have to cast them. Which is bad.
I thought about the following approach which solves the casting issue but couples the classes even further:
public class Container
{
public ResourceA a;
public ResourceB b;
private List<User> users;
public void handleUser(User u)
{
u.useResource(this);
}
}
public abstract class User
{
public abstract void useResource(Container c);
}
public class UserA: User
{
public override void useResource(Container c)
{
useResourceA(c.a);
}
void useResourceA(ResourceA a)
{
//do something with b
}
}
public class UserB: User
{
public override void useResource(Container c)
{
useResourceB(c.b);
}
public void useResourceB(ResourceB b)
{
//do something with b
}
}
Is this a well know anti pattern? Is there a better way to do this?
Aucun commentaire:
Enregistrer un commentaire