what about using a static class with static properties returning new instances of concrete classes extending an abstract one
MyObject has a shape and the shape have to be chosen and passed as argument to the ctor, can't exist a MyObject whitout a shape and the shape can't vary along his life. It happens often in real life.
namespace JackNova.ConsoleClient.Test.Fun
{
abstract class Shape { }
class Circle : Shape { }
class Square : Shape { }
class Triangle : Shape { }
static class Shapes
{
public static Circle Circle { get { return new Circle(); } }
public static Square Square { get { return new Square(); } }
public static Triangle Triangle { get { return new Triangle(); } }
}
class MyObject
{
public Shape Shape { get; private set; }
public MyObject(Shape shape)
{
this.Shape = shape;
}
}
class Test
{
static void Run()
{
MyObject coolOne = new MyObject(Shapes.Circle);
}
}
}
I think I'm violating some principle here, the open closed one for example. My purpose is to simplify developing at design time. As you can see when I instanciate MyObject I don't have to remeber wich kind of objects I can pass as argument but they are instanciated and passed by the abstract class.
Do you thi开发者_如何学JAVAnk this sucks?
It's fine to have an abstract class and a class which takes a reference to an instance of that abstract class in the constructor and sets an effectively-readonly property.
I would question your use of properties in the static class though:
- How do you benefit in usage over just calling
new Circle()
? - If there were a benefit, I think it would still make sense to make these methods instead of properties.
I believe what you are trying to do should be a function of the tool. For example, Visual Studio's IntelliSense would tell you the valid types that can be passed into MyObject.
Also, properties should generally not have any side-effects. So the Circle property should really be a CreateCircle method (or something similar).
I don't know if it violates a principle, but I really like the readability and expressivity of this syntax.
If you consider that shapes are value objects, does it matter that much that each call to Shapes.Circle creates a new Circle ?
精彩评论