Skip to content

Consider using a factory pattern to create instances by string #24

@rignaneseleo

Description

@rignaneseleo

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions