Re: Question on OO Principle
QQ wrote:
1, regarding Open-Close
I think new create a instance so current class changed(not close for
modification)
I'm guessing here, but I think the opposite. "new" violates the open
principle. "new" returns a single concrete class and that can never
change. It is not "open for change".
Solution: factory method. Factory methods can return sub-classes, thus
allowing the design to be extended. They are "open for change."
2, regarding DIP
e.g. List = new ArrayList(). Abstract depends on a concrete instance
now,(in DIP, concret depends on abstract right?)
I'm less sure about this but I think the same here. "new" returns a
concrete class that is not open for extension. DIP may require making a
different class.
ArrayList is not a good example because it is concrete and depends on an
abstract interface, List. So it's well positioned for further extension.
The fact that "new" is often used in the Collection design pattern
doesn't prevent other patterns.
Example:
List list = otherList.subList( from, to );
is a factory method that leaves the concrete type to runtime code. That
doesn't mean it's bad to have to call "new" eventually to get some
object, just that you need flexibility when you decide to call it.