jeudi 20 avril 2017

Adapter pattern in C#

I'm wondering whether I understand this pattern correctly. Let's assume that we have interface incompatibility. Function Printer() from 3rd party dll, requires IHPPrinter, but our object does not implement this interfece... So finally we have got to implement this interface and return our implementation of method, like in code below? :) The second question is, if we don't provide implementation for method DocumentsInQueue, exeception will be thrown. Is some possibility to prevent calling this method?

class Program
{
    static void Main(string[] args)
    {
        EpsonPrinter _epsonPrinter = new EpsonPrinter();
        Printer(_epsonPrinter);
        Console.ReadKey();
    }


    public static void Printer(IHPPrinter hpPrinter)
    {
        hpPrinter.PrintDocument();
    }

    public interface IHPPrinter
    {
        void PrintDocument();
        int DocumentsInQueue();
    }
    public interface IEpsonPrinter
    {
        void Print();
    }

    public class EpsonPrinter : IEpsonPrinter, IHPPrinter
    {
        public int DocumentsInQueue()
        {
            throw new NotImplementedException();
        }

        public void Print()
        {
            this.PrintDocument();
        }

        public void PrintDocument()
        {
            Console.WriteLine("Printing from Epson printer...");
        }


    }
}

Aucun commentaire:

Enregistrer un commentaire