countries_world_map
countries_world_map copied to clipboard
Consider using a factory pattern to create instances by string
Hi, thanks for your impressive work.
I was looking at the example and I saw a switch like this:
String getInstructions(String id) {
switch (id) {
case 'ar':
return SMapArgentina.instructions;
case 'at':
return SMapAustria.instructions;
case 'ad':
return SMapAndorra.instructions;
....
}
That could be more elegantly be replaced (inside the library) with a factory structure like this:
abstract class Animal {
void makeSound();
}
class Dog implements Animal {
void makeSound() => print('Woof!');
}
class Cat implements Animal {
void makeSound() => print('Meow!');
}
// Factory class
class AnimalFactory {
static final Map<String, Animal Function()> _creators = {
'Dog': () => Dog(),
'Cat': () => Cat(),
};
static Animal create(String name) {
if (_creators.containsKey(name)) {
return _creators[name]!();
} else {
throw 'Invalid animal type: $name';
}
}
}
void main() {
var animal = AnimalFactory.create('Dog');
animal.makeSound(); // Outputs: Woof!
}
It basically allows you to create instances using a string ie:
String getInstructions(String id) => SMap.country(id);
What do you think?
Hi @rignaneseleo
Sorry for the late response, I have been starting my own company this year. I love the idea, but at this moment it doesn't have a high priority for me.
If you want to, feel free to submit a PR for this feature. For now I will put it on my "tasks list".