Design mode, description with Delphi-> Reference Count Pattern

zhaozj2021-02-08  222

Reference Count mode (reference number)

origin

The Reference Count mode is a relatively simple, but the practicability is very practical. For example, the reference in COM is the foundation of the COM lifecycle control.

purpose

Use the REFERENCE COUNT mode to control the life cycle of the object. The objects will be available in the reference count, otherwise the object will desire to itself.

motivation

The foundation of the Reference Count mode is very similar to the foundation of the Lock. The only difference is that the LOCK is predefined, fixed. Its specific class is also similar to the LOCK mode. Reference Count Mode Default A Behavioral Method: SetReferenced, you can create your own habits when you use some modes. Such as

The Reference Count mode has a better application in Singleton mode.

application

Unit ReferenceCount;

TrefcountSample = Class (TOBJECT)

Private

Freerencecnt: integer;

protected

Function Reference: Boolean;

Procedure setReferenced (IsReference: Boolean);

public

Procedure addReference;

Procedure RemoveReference;

END;

{

*********************************************************** ************

}

Procedure Trefcountsample.addReference;

Begin

INC (freerencecnt);

If Freferencecnt = 1 Then SetReference (TRUE);

END;

Function Trefcountsample.referenced: Boolean;

Begin

RESULT: = (freerencecnt <> 0);

END;

Procedure trefcountsample.removereference;

Begin

Dec (freerencecnt);

If freferencecnt = 0 THEN SETREFERENCED (FALSE);

END;

Procedure Trefcountsample.setrEference (IsReference: Boolean);

Begin

IF NOT REFERENCED THEN FREE

END;

Delphi Example: IUNKNOWN

Iunknown = interface

['{00000000-0000-0000-C000-000000000046}']

...

Function QueryInterface (Const IID: Tguid; Out Obj): hResult; stdcall;

Function _addref: integer; stdcall;

Function _Release: integer; stdcall;

END;

转载请注明原文地址:https://www.9cbs.com/read-3021.html

New Post(0)