Абстрактный класс в шаблоне дизайна - PullRequest
3 голосов
/ 25 сентября 2011

Для шаблона проектирования фасада в книге Эриха Гамма «Элементы многоразового объектно-ориентированного программного обеспечения», посвященной разностным шаблонам, в части реализации говорится о том, чтобы сделать класс фасада абстрактным классом, поскольку он уменьшает связь между клиентом и подсистемой.

Я не могу понять этот момент.Как создание абстрактного класса помогает уменьшить сцепление.Кто-нибудь, пожалуйста, помогите мне понять это.

Исходный код без класса Фасад как абстрактный класс:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Facade_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Facade facade = new Facade();

            facade.ProcessA();
            facade.ProcessB();

            // Wait for user
            Console.ReadKey();
        }
    }

     /// <summary>
  /// The 'Subsystem ClassA' class
  /// </summary>
  class SubSystemOne
  {
    public void MethodOne()
    {
      Console.WriteLine(" SubSystem One");
    }
  }

  /// <summary>
  /// The 'Subsystem ClassB' class
  /// </summary>
  class SubSystemTwo
  {
    public void MethodTwo()
    {
      Console.WriteLine(" SubSystem Two");
    }
  }

  /// <summary>
  /// The 'Subsystem ClassC' class
  /// </summary>
  class SubSystemThree
  {
    public void MethodThree()
    {
      Console.WriteLine(" SubSystem Three");
    }
  }

  /// <summary>
  /// The 'Subsystem ClassD' class
  /// </summary>
  class SubSystemFour
  {
    public void MethodFour()
    {
      Console.WriteLine(" SubSystem Four");
    }
  }

  /// <summary>
  /// The 'Facade' class
  /// </summary>
  class Facade
  {
    private SubSystemOne _one;
    private SubSystemTwo _two;
    private SubSystemThree _three;
    private SubSystemFour _four;

    public Facade()
    {
        Console.WriteLine("\nRequests received from Client System and Facade is in execution... ");

      _one = new SubSystemOne();
      _two = new SubSystemTwo();
      _three = new SubSystemThree();
      _four = new SubSystemFour();
    }

    public void ProcessA()
    {
      Console.WriteLine("\nProcessA of Facade uses the following subsystems to accomplish the task:");
      _one.MethodOne();
      _two.MethodTwo();
      _four.MethodFour();
    }

    public void ProcessB()
    {
        Console.WriteLine("\nProcessB of Facade uses the following subsystems to accomplish the task:");
      _two.MethodTwo();
      _three.MethodThree();
    }
  }
}

Код с классом Фасад в качестве абстрактного класса:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Facade_abstract
{
    class Program
    {
        static void Main(string[] args)
        {
            FacadeAbs facade = new FacadeAbs();

            facade.ProcessA();
            facade.ProcessB();

            // Wait for user
            Console.ReadKey();

        }
    }

    class SubSystemOne
    {
        public void MethodOne()
        {
            Console.WriteLine(" SubSystem One");
        }
    }

    /// <summary>
    /// The 'Subsystem ClassB' class
    /// </summary>
    class SubSystemTwo
    {
        public void MethodTwo()
        {
            Console.WriteLine(" SubSystem Two");
        }
    }

    /// <summary>
    /// The 'Subsystem ClassC' class
    /// </summary>
    class SubSystemThree
    {
        public void MethodThree()
        {
            Console.WriteLine(" SubSystem Three");
        }
    }

    /// <summary>
    /// The 'Subsystem ClassD' class
    /// </summary>
    class SubSystemFour
    {
        public void MethodFour()
        {
            Console.WriteLine(" SubSystem Four");
        }
    }

    /// <summary>
    /// The 'Facade' class
    /// </summary>
    public abstract class Facade
    {
        //public abstract Facade();

        public abstract void ProcessA();

        public abstract void ProcessB();

    }

    public class FacadeAbs : Facade
    {
        private SubSystemOne _one;
        private SubSystemTwo _two;
        private SubSystemThree _three;
        private SubSystemFour _four;

        public FacadeAbs()
        {
            Console.WriteLine("\nRequests received from Client System and Facade is in execution... ");

            _one = new SubSystemOne();
            _two = new SubSystemTwo();
            _three = new SubSystemThree();
            _four = new SubSystemFour();
        }


        public override void ProcessA()
        {
            Console.WriteLine("\nProcessA of Facade uses the following subsystems to accomplish the task:");
            _one.MethodOne();
            _two.MethodTwo();
            _four.MethodFour();
        }

        public override void ProcessB()
        {
            Console.WriteLine("\nProcessB of Facade uses the following subsystems to accomplish the task:");
            _two.MethodTwo();
            _three.MethodThree();
        }

    }
}

Оба дают вывод в виде:

Requests received from Client System and Facade is in execution...

ProcessA of Facade uses the following subsystems to accomplish the task:
 SubSystem One
 SubSystem Two
 SubSystem Four

ProcessB of Facade uses the following subsystems to accomplish the task:
 SubSystem Two
 SubSystem Three

1 Ответ

3 голосов
/ 25 сентября 2011

Абстрактные классы отделяют интерфейс от реализации, по крайней мере, когда метод размечен как абстрактный или виртуальный.Интерфейсы являются логической крайностью для абстрактных классов, потому что они являются на 100% чистыми, виртуальными, абстрактными методами.

Когда клиент имеет дело с типом интерфейса, он не имеет представления о том, как он реализован.Нет никакого знания о том, как работают абстрактные методы, следовательно, большая развязка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...