The trick is to realize that you're not "creating", "instantiating", or "initializing" an interface. You are simply defining a variable as being something that you know implements that interface.
You are essentially telling other programmers working on this code that for the rest of this method, you are only interested in the fact that myDoc
is a Doc
(i.e., something that satisfies the Doc
interface). This can make programming simpler because the IDE's auto-complete will now only show you the methods that are defined by this interface, rather than everything that a SimpleDoc
is capable of doing.
Imagine that in the future you want to expand your functionality so that you could have different implementations of Doc depending on some input. Rather than creating the SimpleDoc explicitly, you say:
Doc mydoc = docFactory.getByType(inputType);
The docFactory
can produce any type of Doc
, and this method doesn't really care what kind gets instantiated, because it's going to treat it like a Doc
regardless.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…