开发者

How do I create a factory object that does not cause an infinite loop

Whenever I try to create a new CD object I get a stack overflow. I want a parameter to be passed into mediaFactory so that it could be determ开发者_StackOverflowined what type of media is created. Could anyone point out why I might be having problems with this when I do this "Dim media As CD = New CD()"

Thanks

Public MustInherit Class MediaFactory
Inherits MediaContext
Implements IMedia

Public Sub New(ByVal typeId As Integer)
    MyBase.new()
    _mediaTypeId = typeId
End Sub

Private _mediaTypeId As Integer
Public Property mediaTypeId() As Integer Implements IMedia.mediaTypeId
    Get
        Return _mediaTypeId
    End Get
    Set(ByVal value As Integer)
        _mediaTypeId = value
    End Set
End Property

End Class


Public Class CD
Inherits MediaFactory 
Implements IMedia 

Public Sub New() 
    MyBase.New(1) 
End Sub 

Public Sub New(ByVal name As String) 
    MyBase.New(1) 
    MyBase.title = name 
End Sub 

End Class


Public Class MediaContext

Private Shared _strategies As New Dictionary(Of MediaEnum, IMedia)()

Public Sub New()
    _strategies.Add(MediaEnum.CD, New CD())

End Sub

Public Sub New(ByVal name As String)
    _title = name
End Sub

Private _title As String
Public Property title() As String
    Get
        Return _title
    End Get
    Set(ByVal value As String)
        _title = value
    End Set
End Property

End Class


A stack overflow occurs in a case of infinite recursion. This happens when you have method calls like:

Public Sub B()
 A()
End Sub

Public Sub A()
 B()
End Sub

then call A() or B(). The size of the call stack (which keeps track of what sub is currently running, and what sub called it, and so on up to your program's main) grows infinitely until it reaches the limit of available space. (It will look like A > B > A > B > A > B... etc.)

In your case, it seems like your New() method calls New(1), which in turn calls MediaFactory's New(integer), which calls .new(), which calls your factory's New()... hopefully you get the picture.


Its in MediaContext:

Public Sub New()
   _strategies.Add(MediaEnum.CD, New CD())
End Sub

New CD() -> MediaFactory.New(integer) -> MediaContext.New() -> New CD() -> MediaFactory.New(integer) and so on.

There's no reason to creat a new CD when generating a new Media Context, if the Media Context is an ancestor that should have no knowledge of CDs. Either that or MediaFactory should not be inheriting from MediaContext.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜