59.2.2. Abstract Session Pattern

Object-oriented frameworks are structured in terms of client/server relationships between objects; an objects services are invoked by client objects through the operations of its interface. A common design requirement is for a server object to maintain state for each client that it is serving. Typically this is implemented by returning handles or untyped pointers to the client that are used to identify the per-client data structure holding its state. The lack of strong typing can lead to obscure errors that complicate debigging and maintenance.

The Abstract Session pattern provides a way for an object to store per-client state without sacrificing type-safety or efficiency. A service object, rather than providing a client with a handle to be passed as an argument to the operations of its abstract interface instead creates an intermediate "session" object and returns a pointer to the session object bak to the client. The session object encapsulates the state information for the client which owns the session and is only exposed to the client as an abstract interface through which the client can access the service's functionality with full type-safety. When the client invokes operations of the session, the session co-operates with the service object to complete the operation. When the client has finished using the service, it "releases" the session, after which any pointers to the session object are invalid.

Příklad 59.3. Abstract Session Pattern

class Server
    def initialize
	@client_id = 0
    end

    def session
	@client_id += 1
	Session.new( self, @client_id )
    end

    def service_client( session )
	puts "servicing client #{session.client_id}"
    end
end


class Session
    attr :client_id

    def initialize( server, client_id )
	@server = server
	@client_id = client_id
    end

    def service
	@service.service_client( self )
    end
end

server = Server.new
client1 = server.session
client2 = server.session

client1.service
client2.service

# Returns:
# servicing client 1
# servicing client 2

	

Licence Creative Commons
Tento dokument Ruby, jehož autorem je Radek Hnilica, podléhá licenci Creative Commons Uveďte autora-Nevyužívejte dílo komerčně-Zachovejte licenci 3.0 Česká republika .