Consider this example:
Notice what is in the interface part of the unit. There are two things: the interface that is being defined and a global function which returns something implementing that interface. There is no class information whatsoever. The entire implementation of this interface, including the class declaration, is in the implementation section of the unit. This prohibits others from using this class in any other way. They can't extend it, override it or instantiate another copy of it. If they want a different implementation of this interface, they have to completely re-implement it.unit uSomeManager; interface type ISomeManager = interface ... end; function SomeManager: ISomeManager; implementation type TSomeManager = class(TInterfacedObject, ISomeManager) ... end; var gSomeManager: ISomeManager; function SomeManager: ISomeManager; begin if not Assigned(gSomeManager) then gSomeManager := TSomeManager.Create; result := gSomeManager; end;
Whether or not this is a Good Thing is another discussion, but it does make it very clear to the user that it is intended to only have one instance of this. I find it works well for places where you might want to use a singleton, without the low-level messiness normally associated with them in Delphi.
No comments:
Post a Comment
Comments are welcome but I do moderate them. This is simply to keep things wholesome for general family viewing. By default, comments will be accepted. The few things that will cause a comment to be rejected are:
1. It is too long even though it may be well-written and make interesting points. It's supposed to be a comment, not an essay. If you have that much to say, write a blog article and backlink to me.
2. It is nasty, impolite or uses language that is unacceptable.
3. It includes a a link that has a typo or is broken in some other way.
4. It should have been sent as an e-mail since it is clearly addressed to me and does not appear to have been intended for other readers.
5. It is blatantly self-promotional. This does not mean it can't be self-promotional at all, but it should add some value over an above the marketing.