How to 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 the parameter to be passed to mediaFactory so that I can determine what type of media is created. Can someone point out why I might have 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 
+4
source share
2 answers

Stack overflow occurs in case of infinite recursion. This happens when you call method calls, for example:

 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 which sub is currently working, and which one is called under it, etc. Up to your main program) grows indefinitely until it reaches the limit of available space. (It will look like A> B> A> B> A> B ... etc.)

In your case, it seems that your New () method calls New (1), which in turn calls MediaFactory New (integer), which calls .new (), which calls your factory New () ... I hope you get a picture.

+1
source

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), etc.

There is no reason to create a new CD when creating a new media context if the media context is the ancestor that CDs should not know. Either this or MediaFactory should not inherit from MediaContext.

+1
source

Source: https://habr.com/ru/post/1299594/


All Articles