samedi 8 janvier 2022

c# Factory Method some Methods are not accessible

first, sorry for my bad English. I'm learning some design patterns. I try to implement a factory in an example-code. This is the Code.

Program.cs:

namespace Factorymethod_self
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Animal myDog = new Dogs().SummonAnimal();
            myDog.Name = "Rex";
            myDog.Run(); // Isn't working
            myDog.Bark(); // Isn't working
            myDog.Pet(); // Isn't working
        }
    }
}

Animal.cs:

namespace Factorymethod_self
{
    public class Animal
    {
        private string name;

        public string Name
        {
            get => name;
            set => name = value;
        }
    }
}

Mammal.cs:

using System;

namespace Factorymethod_self
{
    public class Mammal : Animal
    {
        public void Run() => Console.WriteLine(Name + " is running");
    }
}

Bird.cs:

using System;

namespace Factorymethod_self
{
    public class Bird : Animal
    {
        public void Fly() => Console.WriteLine(Name + " is flying");
    }
}

GeneralFactory.cs:

using System;

namespace Factorymethod_self
{
    public abstract class GeneralFactory
    {
        public abstract Animal SummonAnimal();

        public void Pet()
        {
            Console.WriteLine("You petted " + SummonAnimal().Name);
        }
    }
}

Dogs.cs:

using System;

namespace Factorymethod_self
{
    internal class Dogs : GeneralFactory
    {
        public void Bark() => Console.WriteLine("The Dog is barking");

        public override Animal SummonAnimal()
        {
            Animal animal = new Mammal();
            return animal;
        }
    }
}

I think, the method Bark() isn‘t accessible, because Animal myDog = new Dogs().SummonAnimal(); doesn’t impellent the class Dogs() but Mammal(). But I Doesn’t understand, why the methods Run() and Pet() aren’t accessible. If I use GeneralFactory myDog = new Dogs();, I can access the Method Pet() but I don’t think, this is how the Factory should work. I’ve added a map for the classes

So, there are my questions.

What am I doing wrong here? How can I try to solve it? Is this even a right factory?

Thank you very much.

Aucun commentaire:

Enregistrer un commentaire