Search code examples
design-patternsfactory-pattern

Alphabet implementation by Factory Method


Does it goo idea to implement alphabet by factory method?

Example:

public class Alphabet
{
    public Alphabet(image picture, string name)
    {
       _picture = picture;
       _name = name;
    }

    public void Show()
    {
       _picture.Show();
    }
}

public LetterA: Alphabet
{
    public LetterA() : Alphabet("lttrA.png", "Letter A"){}
}

....


public LetterZ: Alphabet
{
    public LetterZ() : Alphabet("lttrZ.png", "Letter Z"){}
}

using:

Alphabet ltr1 = new LetterA();

Requirements: pictures will be never change, no adding methods in future

Thanks


Solution

  • Factory method provides a new instance of a class on each invocation. In your case, there's no need to create multiple instances, you can create an enum for the alphabets.

    public enum Alphabet
    {
        A(/*some image*/, "A"),
        B(/*some image*/, "B"),
        C(/*some image*/, "C"),
        D(/*some image*/, "D");
        // ... and so on till Z
    
        private final String name;
        private final Image picture;
    
        private Alphabet(Image picture, String name)
        {
           this.picture = picture;
           this.name = name;
        }
    
        public void Show()
        {
           picture.Show();
        }
    }