What Design Patterns do you implement in common Delphi programming? [closed] - delphi

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What Design Patterns do you implement in common Delphi programming? What patterns are easier to adapt in Delphi programming? (Every language is excellent in different fields, so what patterns are likely to be very strong structures when using Delphi?)
I would be glad, if you could tell about some changes in design patterns for Delphi 2009 / 2010 (since those support generics, and RTTI in 2010).
There are many articles out there in the wild Internet, but they doesn't discuss the everyday usability and changes in patterns. (Most of them just discuss changes in language specifics, architecture).

Only a minority of the Delphi developers knows that every Delphi developer uses a Factory pattern (delphi.about.com has an example in "regular" Delphi), but then implemented using virtual Create constructors.
So: time to shed some light on that :-)
Virtual constructors are to classes like virtual methods are like object instances.
The whole idea of the factory pattern is that you decouple the logic that determines what kind (in this case "class") of thing (in this case "object instance") to create from the actual creation.
It works like this using virtual Create constructors:
TComponent has a virtual Create constructor so, which can be overridden by any descending class:
type
TComponent = class(TPersistent, ...)
constructor Create(AOwner: TComponent); virtual;
...
end;
For instance the TDirectoryListBox.Create constructor overrides it:
type
TDirectoryListBox = class(...)
constructor Create(AOwner: TComponent); override;
...
end;
You can store a class reference (the class analogy to an object instance reference) in a variable of type 'class type'. For component classes, there is a predefined type TComponentClass in the Classes unit:
type
TComponentClass = class of TComponent;
When you have a variable (or parameter) of type TComponentClass, you can do polymorphic construction, which is very very similar to the factory pattern:
var
ClassToCreate: TComponentClass;
...
procedure SomeMethodInSomeUnit;
begin
ClassToCreate := TButton;
end;
...
procedure AnotherMethodInAnotherUnit;
var
CreatedComponent: TComponent;
begin
CreatedComponent := ClassToCreate.Create(Application);
...
end;
The Delphi RTL uses this for instance here:
Result := TComponentClass(FindClass(ReadStr)).Create(nil);
and here:
// create another instance of this kind of grid
SubGrid := TCustomDBGrid(TComponentClass(Self.ClassType).Create(Self));
The first use in the Delphi RTL is how the whole creation process works of forms, datamodules, frames and components that are being read from a DFM file.
The form (datamodule/frame/...) classes actually have a (published) list of components that are on the form (datamodule/frame/...). That list includes for each component the instance name and the class reference.
When reading the DFM files, the Delphi RTL then:
finds about the components instance name,
uses that name to find the underlying class reference,
then uses the class reference to dynamically create the correct object
A regular Delphi developer usually never sees that happen, but without it, the whole Delphi RAD experience would not exist.
Allen Bauer (the Chief Scientist at Embarcadero), wrote a short blog article about this topic as well.
There is also a SO question about where virtual constructors are being used.
Let me know if that was enough light on the virtual Create constructor topic :-)
--jeroen

You can find an excellent article by Marco Cantu on the equivalence of GOF patterns and Delphi idioms. I remember attending his Borcon session on the subject, it was excellent.
One main idea to remember is that design patterns are needed to supplement shortcomings of the language/framework. And if you have a native idiom, you don't need to reinvent the wheel and implement the whole GOF shebang, just learn to recognize it and name it (as Jeroen did with his superb explanation on the Factory).

I use frequently following patterns:
Command
Visitor
Table Data Gateway
Observer
Adapter
Singleton (with many care!)
Abstract Factory
Factory Method
State
Dependency Injection in all of his form
Facade
Service Locator
Separated Interface

I frequently uses the following patterns:
Observer in MVC
Singlton
Template Method
State

Non-OOP programming (some call it Structured programming) is very common with Delphi programmers. It is very simple: You create a function that does something, and it is not related to a record/object-like data structure. Example: IntToStr()
Delphi does this very well, because encapsulation is delivered using interface/implementation sections, and because the resulting machine code is extremely efficient. When compiling, it also supports optimizations for that, for instance, if you have a typed constant in your interface section, and the program is fully compiled - if you then change the value of that constant, the unit is not recompiled, only the constant changes. This is not really necessary in a daily work, but it is an example of how Delphi works.

An ordinary Unit behaves like a singleton. You can't use OOP-techniques like inheritance and polymorfism though, but that might be a good thing :)
I generally think that Delphi makes it too easy to avoid sound oop design. That is nice for RAD, but you need to know which pitfalls to avoid if you want a flixible and maintainable code. Eg the public visibility for the components you add to the forms, the global Form1 variable of type TForm1 (instead of manually managed lifetime and a base class as type) and the lack of seperation between GUI and business logic. Just to mention some issues.

Related

Implement Global interfaces

I'm currently struggling with the following:
I need to create two different DLL's, which do exactly the same but are looking to a different DB. The two DB's are nothing alike.
My dll's should be handling the communication with those different DB's.
So that the main program chooses which dll he wants to use.
I want to be sure each dll has exactly the same procudes/functions/...
I was thinking of using interfaces.
But I can't figure out how to create global interfaces. the dll's belong to the same projectgroup.
I do believe you're making a "mountain out of a molehill" thinking you need 2 different DLLs. But if you choose the last of my suggested options, you should find it fairly easy to switch between a 2 DLL solution and 1 DLL solution.
Option 1
This is the most straightforward:
Create a new unit.
Add your DLL interface (the exports).
Include the unit in both projects.
unit DllExportIntf;
interface
uses
DllExportImpl;
exports DoX;
implementation
end.
Note that this unit uses DllExportImpl which will also have to be included in both projects. However, you'll need 2 different files with the same name in 2 different locations in your file system. So each DLL project will have different implementations.
Now whenever you make a change to your interface, your projects won't compile until you've updated each of the DllExportImpl units.
What I don't particularly like about this solution is the need for units with the same name but different behaviour. Since you intend having both DLLs in the same project group: I should warn you that I've experienced the IDE getting confused by duplicate unit names.
Option 2
Place the exports into a shared include file.
library DllSharedExportsImpl1;
uses
DllExportImpl1 in 'DllExportImpl1.pas';
{$I ..\Common\DllExports.inc}
The DllExports.inc file will only include your exports clauses. E.g.
exports DoX;
This has the advantage that now each DLL can use different unit names for the different implementations. And if you change your include file, neither project will compile until you've updated its implementation unit to accommodate the change.
Note that this does come with its own set of problems. The way includes work: the compiler effectively shoves the contents of the include file into the unit at compile time. So what looks like line 7 to the IDE is entirely different to the compiler. Also editing include files can be a bit of a nuisance because context can only be determined where the file is included making editor support quite impractical.
Option 3
This option is a little more work, but provides much better long-term maintainability.
You do this by implementing your interface via polymorphic objects. In this way, both DllProjects will also share the routines that are actually exported. When each DLL initialises, it sets the concrete implementation to be used.
Your DLL interface could look something like this.
unit DllExportIntf;
interface
type
TAbstractImpl = class(TObject)
public
procedure DoX; virtual; abstract;
end;
procedure AssignDllImpl(const ADllImpl: TAbstractImpl);
procedure DoX;
exports DoX;
implementation
var
GDllImpl: TAbstractImpl;
procedure AssignDllImpl(const ADllImpl: TAbstractImpl);
begin
if Assigned(GDllImpl) then
begin
GDllImpl.Free;
end;
GDllImpl := ADllImpl;
end;
procedure DoX;
begin
GDllImpl.DoX;
end;
end.
When you initialise your DLL, you can call:
AssignDllImpl(TDllImpl_1.Create);
A clear advantage of this approach is that if there is any common code between your 2 DLLs, it can be included in your base implementation. Also, if you can change an existing method DLL in such a way that it does not require a change to TAbstractImpl, you possibly will only need to recompile your DLLs.
Furthermore, if you need to change existing virtual abstract methods, you will have to update the overrides in your concrete implementations accordingly.
WARNING If you add a new virtual abstract method, your projects will still compile with warnings that you are creating objects with abstract methods. However, you should always treat warnings as errors. If you do, this caveat won't be a problem.
NOTE: As mentioned earlier, using this approach you should be able to fairly easily switch between single DLL and 2 DLL solutions. The difference basically boils down to which units are included in the project, and how you initialise the global.
It may also be worthwhile mentioning that you could even eliminate the global altogether by implementing a Handle to use with each of your DLL routines. (Similar to Windows.) Bear in mind that there are technical issues when trying to pass objects between DLL and application code. This is why instead of passing objects, you use a "handles" to objects and encapsulate the actual object instances internally.
Considering all that was said, I believe that you would be more successful if you design your solution with packages, not DLLs. A package is a DLL, but rich in symbols, so Delphi can be a better use of it. Particularly, the symbols declared inside the package will more easily be loaded by your application, with a much higher level of abstraction. It´s what the Delphi IDE uses to load components.
So, following this design, this is what you have to do:
Declare your interfaces in units existing in a package named (for instance) DBServices.dpk. Here is an example of such an unit:
unit DBService1;
interface
uses
....;
type
IService1 = interface
[....] // here goes the GUID
procedure ServiceMethod1;
procedure ServiceMethod2;
// and so on...
end;
implementation
end.
So, above you created an unit that declares an interface. Your aplication can use that interface anywhere, just reference the package in your application and use it in other units and you will have the access to the symbols declared.
Declare the implementation class for that very same interface in another unit of another package, for instance, dedicated to SQLServer (SQLServerServices.dpk):
unit SQLServerService1;
interface
uses
DBService1, ....;
type
TSQLServerService1 = class(TInterfacedObject, IService1)
protected // IService1
procedure ServiceMethod1;
procedure ServiceMethod2;
// and so on...
end;
implementation
procedure TSQLServerService.ServiceMethod1;
begin
// Specific code for SQL Server
end;
procedure TSQLServerService.ServiceMethod2;
begin
// Specific code for SQL Server
end;
...
end.
Above you declared an implementing class for the interface IService1. Now you have two packages, one declaring the interfaces and other implementing those interfaces. Both will be consumed by your application. If you have more implementations for the same interfaces, add other packages dedicated to them.
One important thing is: you have to have a factory system. A factory system is a procedure ou class that will create and return the implementations for your application from each package.
So, in terms of code, in each service package (the ones that implement the interfaces) add a unit named, for instance, xxxServiceFactories, like this:
unit SQLServerServiceFactories;
interface
uses
DBService1;
function NewService1: IService1;
implementation
uses
SQLServerService1;
function NewService1: IService1;
Result := TSQLServerService1.Create;
end;
end.
The code above declares a function that creates the SQL Server implementation and returns it as an interface. Now, if you call a method from the interface returned, you will be actually calling the specific implementation of it for SQL Server.
After loading the package, you will have to link to that function in the very same way you would do if working if a DLL. After you have the pointer for the function, you can call it and you will have the interface in your application's code:
...
var
service1: IService1;
begin
service1 := NewService1;
service1.ServiceMethod1; // here, calling your method!
end;
The model I described in this answer is the one I used in a similar scenario I had to deal with in the past. I presented general ideas that work, but you have to understand the fundamentals of packages and interfaces to really master the technique.
A comprehensive explanation on those matters would be very long for an answer here, but I guess it will be a good starting point for you!
What you want to do is create a COM component project. Define your methods on that & implementations for one DB. Then create a second COM component that uses the same interface.
On the off-chance that your question is more about the fundamentals of Delphi, I've added another answer which may be more helpful to you than the first one. My first answer focused on getting 2 DLLs to expose the same methods (as per the main body of your question). This one focuses on the last 2 sentences of your question:
But I can't figure out how to create global interfaces. The dll's belong to the same project group.
Based on this, it sounds like you're looking for an option to "mark an interface as global so that projects in the same group can use them". Delphi doesn't need a special feature to do this because it's trivially available if you understand certain fundamental principles.
When you create a new unit, it is by default added to the current project. However if you want to share the unit between multiple projects, it's a good idea to save it to a different folder so it's easy to see that it's shared. Your first DLLs project file should look something like this.
library Dll1;
uses
DllSharedIntf in '..\Common\DllSharedIntf.pas';
You can define your "global" interface in the DllSharedIntf unit. E.g.
unit DllSharedIntf;
interface
type
IDllIntf = interface
['{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}']
procedure DoX;
end;
implementation
end.
NOTE: Because the interface type is declared in the interface section of the unit, it is considered "global" because other units are able to use it. But this doesn't automatically make it available to other projects.
You now have to add the shared unit to your other project so it becomes available for use by other units in that project. To do this:
Activate Dll2
Select Project and Add to Project...
Find DllSharedIntf and add it.
Delphi will automatically update your project source file to include the unit.
library Dll2;
uses
DllSharedIntf in '..\Common\DllSharedIntf.pas';
Now in each DLL project you can add a separate implementation unit. E.g. For Dll1:
unit DllImpl1;
interface
uses
//It's very important to indicate that this unit uses the shared unit.
//Otherwise you won't be able to access the "global types" declared
//in the interface-section of that unit.
DllSharedIntf;
type
TDllImpl1 = class(TInterfacedObject,
//Any types defined in the interface-section of any units that
//this unit **uses**, can be accessed as if they were declared
//in this unit.
IDllIntf)
protected
//The fact that this class is marked as implementing the IDllIntf
//means that the compiler will insist on you implementing all
//methods defined in that interface-type.
procedure DoX;
end;
implementation
NOTE This answer only covers sharing an interface between projects. You'll still need to expose the functionality of the DLLs via appropriate exports. You'll need an approach similar to option 3 of my other answer.
Summary
We don't usually talk about "global interfaces" in Delphi. It's generally understood that anything declared in the interface section of a unit is globally accessible. (We do make more of an issue about global variables due to their dangers though; but that's an entirely different topic.)
In Delphi:
Whenever you want one unit (A) to make use of functionality defined in another unit (B), you need to add unit B to the uses clause of unit A.
Whenever you want a project to use a unit created in another project, you need to add the unit to the project. (TIP: It's a good idea to put such units in a separate folder.)
NOTE: When sharing units between projects, the project group is actually irrelevant. Projects don't need to be in the same group to share units. All you need to do is ensure the project can access the unit so that other units in your project can uses it.

Delphi extending class

first of all, sorry if the title is a bit confusing.
i'm planning to develop a small erp application. this apllication will use plugins/addons. this addon might add or extend some modules of the base application.
for example, i have TCustomer class with property "id", and "name".
addon 1 will add a property "dateofbirth".
addon 2 will add a property "balance" and a method "GetBalance".
addon 1 and addon 2 are not aware of each other. addon 1 might be installed and not addon 2 or vice versa. so both addons must inherit the base tcustomer class.
the problem is when both addon are installed. how do i get extended properties in both addons? i will also have to extend the form to add controls to show the new properties.
can it be done using delphi? what is the best way to achieve this? maybe you can point me to some articles of examples?
thanks and sorry for my poor english
Reynaldi
Well, as you are already aware, you can't have more than one plug-in extend an existing class by inheritance. It would confuse the heck out of any app, including any programmer's dealing with the code.
What you need is some type of register mechanism in your TCustomer class where every plugin can register its specific properties, or provide a couple of call back functions for when a TCustomer instance is created (initialized), loaded, stored, or deleted. The core TCustomer after all really doesn't need to know more about the plug-in's than the fact that they might exist.
Depending on how you intend to load/store your data, the core TCustomer class doesn't even have to be aware of the extensions. It would be quite sufficient to make the persistence mechanism aware of plug-ins and provide a way for them to register a call back function to be called whenever a TCustomer / TOrder / TWhatever is initialized / loaded / saved / deleted.
You will also have to make the GUI aware of the plugins and provide the means for them to register pieces of UI to have the main GUI create an extra tab or some such for each plug-in's specific controls.
Sorry no code example. Haven't yet implemented this myself, though I thought about the design and it is on my list of things to play around with.
That said, to give you an idea, the basic mechanism could look something like this:
TBaseObject = class; // forward declaration
// Class that each plug-in's extensions of core classes needs to inherit from.
TExtension = class(TObject)
public
procedure Initialize(aInstance: TBaseObject);
procedure Load(aInstance: TBaseObject);
procedure Store(aInstance: TBaseObject);
procedure Delete(aInstance: TBaseObject);
end;
// Base class for all domain classes
TBaseObject = class(TObject)
private
MyExtensions: TList<TExtension>;
public
procedure RegisterExtension(const aExtension: TExtension);
procedure Store;
end;
procedure TBaseObject.RegisterExtension(const aExtension: TExtension);
begin
MyExtensions.Add(aExtension);
end;
procedure TBaseObject.Store;
var
Extension: TExtension;
begin
// Normal store code for the core properties of a class.
InternalStore;
// Give each extension the opportunity to store their specific properties.
for Extension in MyExtensions do
Extension.Store(Self);
end;
Such an "evolving" class is some kind of multi-inheritance.
I think you shall better use interfaces instead of classes.
That is, each plug-in will serve a class implementation, but you will work with interfaces, and an interface factory.
See this article about "why we need interfaces", or this article from our blog about interfaces and a comparison with classes.
You can test if a class implements an interface: for a plug-in system like yours, this is probably the best way to implement an open implementation. Duck typing is very suitable for plug-ins. The whole Delphi IDE (and Windows itself) is using interfaces for its plug-in systems (via COM for Windows). For a less strong implementation pattern, you can use not interfaces, but late bindings: see the answer of this SO question.
Take a look at the SOLID principles, especially the single responsibility principle. Your question directly breaks this principle: you attempt to mix client personal information (like name) and accounting (like a balance). If your project grows up, you'll probable be stuck by such a design.

How do I determine the type of the implementing object of an interface

I'm attempting to write a unit test for a simple factory class that creates one of several possible implementing objects and returns it as an interface reference.
DUnit has a built in procedure, CheckIs(AObject: TObject; AClass: TClass; msg: string), that based on its name and the parameters it accepts should fail the test if the object's class type doesn't match the expected one. The only problem is it requires an object reference not an interface reference.
So I'm trying to use CheckTrue and perform the comparison in the body of the test but I'm not as familiar with Delphi's type checking support as I am with C#'s.
I know the is operator is out of the question since it only works with object references.
CheckTrue(LMyInterfaceReference {comparison here} TMyClass);
Any suggestions?
BTW, I'm using Delphi 2009 so I don't have access to the new RTTI support added in 2010+.
I'm wondering why you MUST have to test this... maybe you really don't have to.
But if knowing the underlying object of a Interface is a must, you have two choices:
Add a method to the interface which returns the underlying object, just a TObject, and implement this in each class just by returning self.
Hack a bit, for example using this Interface to object routine.
If you don't like hacks and don't feel like upgrading to Delphi 2010+ you may use an interface like this:
IImplementingObjectInterface = interface
function GetImplementingObject: TObject;
end;
Make sure your objects also implement this interface and use it to extract the implementing object. If you need to do this for a lot of objects you can define your own TInterfacedObject derivate that already implements this so you can simply change your inheritance and be done.
Barry Kelly (one of the main Embarcadero Delphi Compiler Engineers) wrote a nice An ugly alternative to interface to object casting this week.
It answers your question.
The fun is that Hallvard Vassbotn wrote a very similar piece of code back in 2004.
From Delphi 2010 on, you can just use an is check or as cast to go back from interface references to object references.
--jeroen

getting around circular references in Delphi [duplicate]

This question already has answers here:
Delphi Enterprise: how can I apply the Visitor Pattern without circular references?
(4 answers)
Closed 8 years ago.
Is there a way of getting around circular unit references in Delphi?
Maybe a newer version of delphi or some magic hack or something?
My delphi project has 100 000+ lines of code mostly based on singleton classes. I need to refactor this, but that would mean several months of "circular reference" hell :)
I've been maintaining close to a million lines of legacy code for the past 10 years so I understand your pain!
In the code that I maintain, when I've encountered circular uses, I frequently have found that they are caused by constants or type definitions in unit A that are needed by unit B. (Sometimes it's also a small bit of code (or even, global variables) in Unit A that is also needed by unit B.
In this situation (when I'm lucky!) I can carefully extract those parts of the code into a new unit C that contains the constants, type definitions, and shared code. Then units A and B use unit C.
I post the above with some hesitance because I'm not an expert on software design and realize there are many others here who are far more knowledgeable than I am. Hopefully, though, my experience will be of some use to you.
It seems you have quite serious code design issues. Besides many signs of such issues, one is the circular unit reference. But as you said: you cannot refactor all the code.
Move all what is possible to the implementation section. They are allowed to have circular references.
To simplify this task you can use 3rd party tools. I would recommend
Peganza Pascal Analyzer - it will suggest what you can move to the implementation section. And will give you many more hints to improve your code quality.
Use the implementation section uses whenever possible, and limit what's in the interface uses clause to what has to be visible in the interface declarations.
There is no "magic hack". Circular references would cause an endless loop for the compiler (unit A requires compiling unit B which requires compiling unit A which requires compiling unit B, etc.).
If you have a specific instance where you think you cannot avoid circular references, edit your post and provide the code; I'm sure someone here can help you figure out how to get it fixed.
There is many ways to avoid circular references.
Delegates.
Way too often, an object will execute some code that should be done in an event instead than being done by the object itself. Whether it is because the programmer working on the project was too short on time(aren't we always?), didn't have enough experience/knowledge or was just lazy, some code like this eventually end up in applications. Real world exemple : TCPSocket component that directly update some visual component on the application's MainForm instead of having the main form register a "OnTCPActivity" procedure on the component.
Abstract Classes/Interfaces. Using either of them allow to remove a direct dependance between many units. An abstract class or an interface can be declared alone in its own unit, limiting dependancies to a maximum. Exemple: Our application has a debug form. It has uses on pretty much the whole application as it displays information from various area of the application. Even worse, every form that allows to show the debug form will also also end up requiring all the units from the debug form. A better approach would be to have a debug form which is essentially empty, but that has the capacity to register "DebugFrames".
TDebugFrm.RegisterDebugFrame(Frame : TDebugFrame);
That way, the TDebugFrm has no dependancies of its own (Except than on the TDebugFrame class). Any and all unit that requires to show the debug form can do so without risking to add too many dependancies either.
There are many other exemple... I bet it could fill a book of its own. Designing a clean class hierarchy in a time efficient fashion is pretty hard to do and it comes with experience. Knowing the tools available to achieve it and how to use them is the 1st step to achieve it. But to answer your question... There is no 1-size-fit-all answer to your question, it's always to be taken on a case by case basis.
Similar Question: Delphi Enterprise: how can I apply the Visitor Pattern without circular references?
The solution presented by Uwe Raabe uses interfaces to resolve the circular dependency.
Modelmaker Code Explorer has a really nice wizard for listing all the uses, including cycles.
It requires that your project compiles.
I agree with the other posters that it is a design issue.
You should carefully look at your design, and remove unused units.
At DelphiLive'09, I did a session titled Smarter code with Databases and data aware controls which contains quite few tips on good design (not limited to DB apps).
--jeroen
I found a solution that doesn't need the use of Interfaces but may not resolve every issues of the circular reference.
I have two classes in two units: TMap and TTile.
TMap contains a map and display it using isometric tiles (TTile).
I wanted to have a pointer in TTile to point back on the map. Map is a class property of TTile.
Class Var FoMap: TObject;
Normaly, you will need to declare each corresponding unit in the other unit... and get the circular reference.
Here, how I get around it.
In TTile, I declare map to be a TObject and move Map unit in the Uses clause of the Implementation section.
That way I can use map but need to cast it each time to TMap to access its properties.
Can I do better? If I could use a getter function to type cast it. But I will need to move Uses Map in the Interface section.... So, back to square one.
In the Implementation section, I did declare a getter function that is not part of my class. A Simple function.
Implementation
Uses Map;
Function Map: TMap;
Begin
Result := TMap(TTile.Map);
End;
Cool, I thought. Now, every time I need to call a property of my Map, I just use Map.MyProperty.
Ouch! Did compile! :) Did not work the expected way. The compiler use the Map property of TTile and not my function.
So, I rename my function to aMap. But my Muse spoke to me. NOOOOO! Rename the Class Property to aMap... Now I can use Map the way I intented it.
Map.Size; This call my little function, who typecast aMap as TMap;
Patrick Forest
I gave a previous answer but after some thinking and scratching I found a better way to solve the circular reference problem. Here my first unit who need a pointer on an object TB define in unit B.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, b, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
FoB: TB;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
FoB := TB.Create(Self);
showmessage(FoB.owner.name);
end;
end.
Here the code of the Unit B where TB has a pointer on TForm1.
unit B;
interface
Uses
dialogs, Forms;
type
TForm1 = class(TForm);
TB = class
private
FaOwner: TForm1;
public
constructor Create(aOwner: TForm);
property owner: TForm1 read FaOwner;
end;
implementation
uses unit1;
Constructor TB.create(aOwner: TForm);
Begin
FaOwner := TForm1(aOwner);
FaOwner.Left := 500;
End;//Constructor
end.
And here why it compiles. First Unit B declare the use of Unit1 in the implementation section. Resolving immediately the circular reference unit between Unit1 et Unit B.
But to allow Delphi to compile, I need to give him something to chew on the declaration of FaOwner: TForm1. So, I add stub class name TForm1 who match the declaration of TForm1 in Unit1.
Next, when come the time to call the constructor, TForm1 is able to pass itself has the parameter. In the constructor code, I need to typecast the aOwner parameter to Unit1.TForm1. And voilà, FaOwner his set to point on my form.
Now, if the class TB need to use FaOwner internally, I don't need to typecast it every time
to Unit1.TForm1 because both declaration are the same. Note that you could set the declaration of to constructor to
Constructor TB.create(aOwner: TForm1);
but when TForm1 will call the constructor and pass itself has a parameter, you will need to typecast it has b.TForm1. Otherwise Delphi will throw an error telling that both TForm1 are not compatible. So each time you call the TB.constructor you will need to typecast to the appropriate TForm1. The first solution, using a common ancestor, his better. Write the typecast once and forget it.
After I posted it, I realized that I made a mistake telling that both TForm1 were identical. They are not Unit1.TForm1 has components and methods that are unknown to B.TForm1. Has long TB doesn't need to use them or just need to use the commonality given by TForm you're okay. If you need to call something particular to UNit1.TForm1 from TB, you will need to typecast it to Unit1.TForm1.
I try it and test it with Delphi 2010 and it compiled and worked.
Hope it will help and spare you some headache.

TFrame inheritance refactoring

Yet another TFrame IDE-registered-component question from me. Thanks for all the help, fellow programmers. : )
Playing around with Darrian's TFrame inheritance suggestion here:
Specifics:
Basically, I have a TFrame-based component that I've registered to the IDE, and it has worked wonderfully. I'm now developing a few "sister" components which will share a great deal of the existing component's non-visual functionality and properties. It makes sense, then, to move a lot of that to a parent/superclass which both the new and the old components can then inherit from.
What is the best way to "refactor" TFrame inheritance in this way? (This may apply to TForm-class descendants too, not sure). What are the caveats and things to watch out for?
Example:
I tried, for example, creating a new TFrame, with nothing on it, and calling that frame TMyBaseFrame. Then modified the class definition of my existing component (Let's call it TMyFrameTreeView) to inherit from that rather than TFrame.
It compiled fine, but when I tried dropping it on a form, I got "ClientHeight not found" (or "ClientHeight property not found"), and it wouldn't drop on the form. Deleting ClientHeight and ClientWidth from the related DFM wreaked havoc, and they ended up replaced upon resizing anyway. I noticed ExplicitHeight and ExplicitWidth in descendent classes, and am thinking that relates to property-value overrides from inherited values, but am not sure. Recreating an entirely new frame via New -> Inherited Items, and then copying everything over, hasn't yielded great results yet either.
Final Note
I realize this could get messy quickly, with streaming DFM files and multiple generations of descendants, etc.... which is part of why I'm asking for the overall "things to look out for" conceptual aspect, but also giving a specific real-world simpler version of the problem as well (which seems to me, ought to be doable).
I've created a little test package to hack around in learning attempts, and am learning a great deal, but it's slow-going, and any guidance/insight from you Delphi "Jedi Masters" out there would be MOST appreciated. : )
Answer update later:
Both of the answers below were helpful. As well, creating a "Base Frame Class" which has NO changes from the normal TFrame, and THEN inheriting from that before adding any properties, methods, etc. seems to stabilize the inheritance streaming tremendously. Not sure why, but so far it has.
In addition to changing base class of TMyFrameTreeView to TMyBaseFrame change the first word in the dfm file for TMyFrameTreeView from object to inherited.
I'm now developing a few "sister"
components which will share a great
deal of the existing component's
non-visual functionality and
properties. It makes sense, then, to
move a lot of that to a
parent/superclass which both the new
and the old components can then
inherit from.
What is the best way to "refactor"
TFrame inheritance in this way?
The crux of your text above perhaps is "component's non-visual functionality". So, in this case, IMHO it's best to separate the visual and non-visual layers.
So, perhaps it's better to use a decorator:
TMySharedEngine = class(Whatever)
property LinkedFrame: TFrame;
property P1;
property P2;
...
procedure Proc1;
procedure Proc2;
... //etc.
end;
and in your 'sister' frames to use instances of it:
var
TMyFrame1 = class(TFrame)
...
FDecorator: TMySharedEngine;
...
public
property MySharedPart: TMySharedEngine read FDecorator;
constructor Create(AOwner: TComponent); override;
...
end;
constructor TMyFrame1.(AOwner: TComponent); override;
begin
inherited;
FDecorator:=TMySharedEngine.Create; //ok, ok do not forget to Free it .Destroy
FDecorator.LinkedFrame:=Self;
...
end;
OTOH, if you want to use your approach you can use Visual Form Inheritance (as Darian suggested) or (more flexible) you can do it by hand: Create, using the IDE the following frames: TBaseFrame, TChildFrame1, TChildFrame2 ... etc. Now go on TChildFrame1's unit and change by hand it's class definition from TChildFrame1 = class(TFrame) to TChildFrame1 = class(TBaseFrame). Compile. It should work. It's recommended though that when you'll do this trick TBaseFrame to be empty in order to avoid possible small quirks (feature collisions etc.)
HTH.

Resources