Jump to content

Singleton Classes


LogSistemas01

Recommended Posts

Hello, I'm starting at Unigui and converting a class, a Singleton.

How to deal with this in Unigui, since it will have the same value between sessions and I need it to be different.

It is a User class, where I store data and permissions, but I have other cases as well.

I saw in the manual, an example where a record was created in MainModule, I would not like to have this 'dependency' there, is there another way to do this? Making my class a singleton per session ?

Follow my class to analyze.

type
  TSystem = class
  private
    constructor Create;
    destructor Destroy; override;
    class var FCompany: TCompanyController;
    class var FUser: TUserController;
  public
    class function LogIn(CompanyID: integer = 0; UserID: integer = 0): TCompanyController;
    class function LoggedUser: TCompanyController;
    class function LoggedCompany: TUserController;
  end;

implementation


{ TSistema }

constructor TSystem.Create;
begin

end;

destructor TSystem.Destroy;
begin
  inherited;
end;

class function TSystem.LoggedUser: TCompanyController;
begin
  FCompany.RefreshConn;
  Result := FCompany;
end;

class function TSystem.LogIn(CompanyID: integer = 0; UserID: integer = 0): TCompanyController;
begin
  try
    {Colocar destroy das classes no logout e finalization}

    if not Assigned(FUser) then
      FUser := TUserController.Create;

    if not Assigned(FCompany) then
      FCompany := TCompanyController.Create;

    FCompany.Get( CompanyID );
    FUser.Get( UserID, CompanyID);

    Result := FCompany;
  except
    on E: Exception do
    begin
      Raise;
    end;
  end;
end;

class function TSystem.LoggedCompany: TUserController;
begin
  if not Assigned( FUser ) then
    raise Exception.Create('FUsuarioLogado não instanciado, realize o login na empresa!');

  FUser.RefreshConn;
  Result := FUser;
end;

initialization

finalization
  if Assigned(TSystem.FCompany) then
    FreeAndNil(TSystem.FCompany);

  if Assigned(TSystem.FUser) then
    FreeAndNil(TSystem.FUser);


end.

Example:

Open 2 Sessions

 

1º Session

TSystem.LogIn(1,1);

ShowMessage(TSystem.LoggedUser.User.Name);

Shows 'User 1'.

 

2º Session

TSystem.LogIn(2,2);

ShowMessage(TSystem.LoggedUser.User.Name);

Shows 'User 2'

 

On 1º Session

ShowMessage(TSystem.LoggedUser.User.Name);

Also shows 'User 2'

 

Thank you!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...