[Twisted-Python] design pattern advice needed

Glenn Hochberg gah at research.att.com
Wed Sep 13 21:47:56 EDT 2006


On Sep 13, 2006, at 5:14 PM, Jonathan Vanasco wrote:

> I can't wrap my head around this
>
> 	FactoryA needs an object from FactoryB
> 	FactoryB has a finite pool of objects, which can be checked in and  
> checked out
>
> I need FactoryA to not-progress until FactoryB is ready to dispense  
> an object.
>
> in all of my attempts, i end up with a deferred object in the  
> Factory A code.
>
> can anyone point me in the right  direction?

Here's a stab at the idea.

class FactoryB:
	product = B
	pool = [ self.product() for _ in range(0,10) ]
	queue = []

	def allocate( self ):
		if not self.pool:
			d = defer.Deferred()
			self.queue.append( d )
			return d
		else:
			return defer.succeed( self.pool.pop() )

	def free( self, p ):
		if self.queue:
			d = self.queue.pop( 0 )
			d.callback( p )
		else:
			self.pool.append( p )

class FactoryA:
	product = A
	factoryB = FactoryB()
	
	def allocate( self ):
		d = self.factoryB.allocate()
		d.addCallback( self._gotB )
		return d

	def _gotB( self, b )
		a = self.product()
		a.b = b
		return a

def _gotA( a ):
	# do something with the A object

def main():
	factoryA = FactoryA()
	d = factoryA.allocate()
	d.addCallback( _gotA )

Maybe others will have a more refined explanation.




More information about the Twisted-Python mailing list