Should I use a singleton class that inherits from an instantiable class or there's another better pattern? - functional-programming

I've got a class called ArtificialIntelligenceBase from which you can create your own artificial intelligence configuration sending some variables to the constructor or you can make a class that inherits from ArtificialIntelligenceBase and in the constructor of this new class just call the function super() with the parameters of the configurations.
I've also created some examples of artificial intelligences in classes, AIPassive, AIAgressive and AIDefensive. Obviously all of them inherits from ArtificialIntelligenceBase.
The point is that there're only few public functions in the base class. The variables in the base class are read only and the non public functions are protected in case you need to apply some modifications on them when created another pre-defined AI.
You can also create another AI just calling the base class sending some parameters in the constructor like this: new ArtificialIntelligenceBase(param1, param2, param3, param4);
I've tought about make the classes as a singleton because the classes can never change and once setted, their variables never change.
The question is: Is the singleton the best pattern to do this? Because I'm not sure.
PD: You don't need to explain any patter, just mention the name and I'll search for how it works
PPD: I'm developing in AS3. Just in case it helps
Thanks

In general, singletons are evil. I don't see any reason in your case to use a singleton, either. It sounds like you're using your own version of a factory method pattern (using a constructor somehow?) or maybe a prototype (I don't know AS3 one bit), but if you're looking for other patterns a couple of other ones are abstract factory and builder.
You don't need to use the singleton pattern to limit yourself to using only one instance per type of class, though. It doesn't help avoid redundancy.

Related

Defining and implementing interfaces in R

I'm interested in defining and inheriting from interfaces in R. By interface, I mean OOP interfaces. I know R supports class extension. This link http://adv-r.had.co.nz/OO-essentials.html gives an example of extending a reference class in R. It defines a NoOverdraftAccount reference class that extends an Account reference class.
Instead of extending the Account reference class, I'd like to be able to define an account interface, IAccount. I would like I'd like NoOverDraftAccount to implement IAccount, such that:
NoOverDraftAccount must implement all methods in IAccount.
NoOverDraftAccount cannot declare any new public methods not already declared in IAccount.
NoOverDraftAccountcan declare private methods and properties.
What's the best way to achieve this?
The closest I've come to an answer was from the question Multiple inheritance for R6 classes. But, the question wasn't focused on interfaces.
Thanks for your time.
I don't think "declarations" make much sense in an interpreted language like R. As there's no compile step there's no way to test if something actually conforms to a declared interface without running a function on the class, something like does_class_follow(class,interface), at some point.
So I think you have to start from scratch - you need to define an interface specification class and write the does_class_follow function.
My first thought was that a class would have to know what interface(s) it conformed to so that the test could introspect this, but perhaps that's wrong and you should have a file of interface definitions and pseudo-declarations that tested everything.
For example, have some file interfaces.R that looks like:
IAccount = Interface(
public = list("deposit","withdraw")
)
Implements(Account, IAccount)
Implements(Account, NoOverDraftAccount)
Then when the package is loaded those Implements functions would run and test the classes against that specification of what an Account interface is. Whether its better to test at load time or to put these sort of things in the ./test/ folder and test them at test time using test_that or another test system is a question...
As you may be aware you'll have to implement this separately for all the OO systems in R that you want to use - S3, S4, R5, ReferenceClasses, R6, proto, R.oo and all the other ones I've forgotten...

noSuchMethod for class Methods (a.k.a. static methods)

I've been using dart for quite a while now. If I want to implement dynamic getters, setters and functions for objects of a class, I can make use of the noSuchMethod-method. But what if I now want to have such a dynamic getter, setter of method on class layer? In Ruby, for example, if one wants to implement a dynamic class method, one would define the method_missing-method on the class object, like for example:
class Test
def self.method_missing
//Do some matching, return result or error
end
end
How would I achieve this in Dart?
I don't think you can do this in Dart without mirrors/reflection.
I also don't think this is very useful.
You can't call a static method on a 'dynamic' type and therefore you can't mock static methods.
If you need this you should just make it a normal method instead of a static one.
You can just override noSuchMethod as noticed here

Understanding the use of Interfaces and Base Classes

I know there are a number of post out there on Interfaces and Base classes, but I'm having a hard time getting the correct design pattern understanding.
If I were to write a reporting class, my initial though would be to create an interface with the core properties, methods, etc. that all reports will implement.
For example:
Public Interface IReportSales
Property Sales() As List(Of Sales)
Property ItemTotalSales() As Decimal
End Interface
Public Interface IReportProducts
Property Productss() As List(Of Inventory)
Property ProductsTotal() As Decimal
End Interface
Then I assume I would have a class to implement the interface:
Public Class MyReport
Implements IReportSales
Public Property Sales() As System.Collections.Generic.List(Of Decimal) Implements IReportItem.Sales
Get
Return Sales
End Get
Set(ByVal value As System.Collections.Generic.List(Of Decimal))
Items = value
End Set
End Property
Public Function ItemTotalSales() As Decimal Implements IReport.ItemTotalSales
Dim total As Decimal = 0.0
For Each item In Me.Sales
total = total + item
Next
End Function
End Class
My thought was that it should be an interface because other reports may not use "Items", this way I can implement the objects that are used for a given report class.
Am I way off? should I have still have just created a base class? My logic behind not creating a base class was that not all report classes may use "Items" so I didn't want to define them where they are not being used.
To attempt to answer you question, abstract classes are used to provide a common ancestor for related classes. An example of this in the .Net API is TextWriter. This class provides a common ancestor all various classes whose purpose is to write text in some fashion.
Interfaces are more properly used to act as adapters for different objects that don't belong in the same "family" of objects but have similar capabilities. A good example of this can be seen with the various collections in the .Net API.
For example, the List and Dictionary classes provide the ability for you to manage a collection of objects. They do not share a common ancestor by inheritance, this wouldn't make sense. In order to allow easy interop between them though, they implement some of the same interfaces.
Both classes implement IEnumerable. This cleanly allows you use objects of either type List or Dictionary as an operand for anything that requires an IEnumerable. How wonderful!
So now in your case in designing new software you want to think about how this would fit into your problem space. If you give these classes a common ancestor via inheritance of an abstract class you have to be sure that all the items that inherit from it are truly of the base type. (A StreamWriter is a TextWriter, for example). Inappropriate use of class inheritance can make your API very difficult to build and modify in the future.
Let's say you make an abstract class, ReportBase, for your repots. It may contain a few very generic methods that all reports simply must have. Perhaps it simply specifies the method Run()
You then only have one type of report you want to make so you define a concrete Report class that inherits from ReportBase. Everything is great. Then you find out you need to add several more types of reports, XReport, YReport, and ZReport for sake of example. It doesn't really matter what they are, but they work differently and have different requirements. All of the reports generate pretty HTML output and everyone is happy.
Next week your client says they want XReport and YReport to be able to output PDF documents as well. Now there are many ways to solve this, but obviously adding an OutputPdf method to your abstract class is a poor idea, as some of those reports shouldn't or can't support this behavior!
Now this is where interfaces could be useful to you. Let's say you define a few interfaces IHtmlReport and IPdfReport. Now the report classes that are supposed to support these various output types can implement those interfaces. This will then let you create a function such as CreatePdfReports(IEnumerable<IPdfReport> reports) that can take all reports that implement IPdfReport and do whatever it needs to do with them without caring what the appropriate base type is.
Hopefully this helps, I was kind of shooting from the hip here as I'm not familiar with the problem you're trying to solve.
Yes, if you don't know how many reports are not going to use Items , you can go for Abastract class.
Another good thought follows:
You can also create both Interface and Abstract class
Define Sales in Interface , create two abstract classes , one for Reports that implement both and another for Report not implementing Sales. Implement interface for both
define both method (implement sales) in first and only implement sales in second.
Give appropriate names to both Abstract classes e.g. ReportWithItemsBase or ReportWithoutItemsBase.
This way you can also achieve self explaining named base classes on deriving Report classes as well.

Utility class or Common class in asp.net

Do anyone knows about the class which has the common function which we generally use while developing web application. I have no idea what you may call it, it may be the utility class or common function class. Just for reference, this class can have some common function like:
Generate Random number
Get the file path
Get the concatinated string
To check the string null or empty
Find controls
The idea is to have the collection of function which we generally use while developing asp.net application.
No idea what you are really asking, but there already are ready-made methods for the tasks you write in various library classes:
Random.Next() or RNGCryptoServiceProvider.GetBytes()
Path.GetDirectoryName()
String.Concat() or simply x + y
String.IsNullOrEmpty()
Control.FindControl()
Gotta love the intarwebs - An endless stream of people eager to criticize your style while completely failing to address the obvious "toy" question. ;)
Chris, you want to inherit all your individual page classes from a common base class, which itself inherits from Page. That will let you put all your shared functionality in a single place, without needing to duplicate it in every page.
In your example it looks like utility class - it is set of static functions.
But I think that you should group it in few different classes rather than put all methods in one class - you shouldn't mix UI functions(6) with string functions(3,4), IO functions (2) and math(1).
As Mormegil said - those functions exists in framework, but if you want to create your own implementations then I think that for part of your function the best solution is to create extension method.

When should the factory pattern be used?

Just as the title asks, when should a trigger in your head go off signifying "Aha! I should use the factory pattern here!"? I find these moments will occur with many other design patterns, but never do I stop myself and think about this pattern.
Whenever you find yourself with code that looks something like this, you should probably be using a factory:
IFoo obj;
if ( someCondition ) {
obj = new RegularFoo();
} else if ( otherCondition ) {
obj = new SpecialFoo();
} else {
obj = new DefaultFoo();
}
The factory pattern is best employed in situations where you want to encapsulate the instantiation of a group of objects inside a method.
In other words, if you have a group of objects that all inherit from the same base class or all implement the same interface that would be an instance where you would want to use the factory pattern (that would be the "pattern" you would look for).
I can think of two specific cases that I think of the factory pattern:
When the constructor has logic in it.
When I don't want the application to worry about what type gets instantiated (eg, I have an abstract base class or interface that I am returning).
Quoted from GoF:
Use the Factory Method pattern when
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the object it creates
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
I highly recommend the GoF book. It has a section on the applicability of each of the 23 patterns it covers.
Are you talking about Factory Method or Abstract Factory?
The basic problem that both solve is letting clients specify the exact class that framework code constructs. For example, if you provide an interface, that clients can implement, and then in your code have something like:
IMyInterface x = new ConcreteClass();
There is no way for clients to change the exact class that was created without access to that code.
A Factory Method is a virtual method that constructs a concrete class of a specific interface. Clients to your code can provide an object that overrides that method to choose the class they want you to create. It might look like this in your code:
IMyInterface x = factory.Create();
factory was passed in by the client, and implements an interface that contains Create() -- they can decide the exact class.
Abstract Factory should be used if you have hierarchies of related objects and need to be able to write code that only talks to the base interfaces. Abstract Factory contains multiple Factory Methods that create a specific concrete object from each hierarchy.
In the Design Patterns book by the Gang of Four, they give an example of a maze with rooms, walls and doors. Client code might look like this:
IRoom r = mazeFactory.CreateRoom();
IWall nw = mazeFactory.CreateWall();
IWall sw = mazeFactory.CreateWall();
IWall ew = mazeFactory.CreateWall();
IWall ww = mazeFactory.CreateWall();
r.AddNorthWall(nw);
r.AddSouthWall(sw);
r.AddEastWall(ew);
r.AddWestWall(ww);
(and so on)
The exact concrete walls, rooms, doors can be decided by the implementor of mazeFactory, which would implement an interface that you provide (IMazeFactory).
So, if you are providing interfaces or abstract classes, that you expect other people to implement and provide -- then factories are a way for them to also provide a way for your code to construct their concrete classes when you need them.
Factories are used a lot in localisation, where you have a screen with different layouts, prompts, and look/feel for each market. You get the screen Factory to create a screen based on your language, and it creates the appropriate subclass based on its parameter.

Resources