jueves, 14 de mayo de 2020

Using delegates. Basic Example


MULTICAST


ENCAPSULATION






class Program
    {
        static void Main(string[] args)
        {
            BookDb books = new BookDb();
            AddBooks(books);            
            Console.WriteLine("Soft cover book titles:");
            books.SearchSoftCoverBooks(PrintTitle);

            Total sum = new Total();
            books.SearchSoftCoverBooks(sum.CalculateTotalPrice);
            Console.WriteLine("Cumulative total price: {0}", sum.total.ToString());

            Console.ReadKey();
        }

        static void PrintTitle(Book book)
        {
            Console.WriteLine(" > {0}", book.title);
        }
        static void AddBooks(BookDb db)
        {
            db.AddBook("C programming", "Brian W.", 19.95m, true);
            db.AddBook("Unix 2.0", "William G.", 25.50m, true);
            db.AddBook("MS-DOS", "Smith E.", 12.75m, false);
            db.AddBook("Cleam code", "Nicholson A.", 22.50m, true);
        }
    }

    public class BookDb
    {
        ArrayList db = new ArrayList();

        public void AddBook(string title, string owner, decimal price, bool softCover)
        {
            db.Add(new Book(title, owner, price, softCover));
        }

        public void SearchSoftCoverBooks(SearchBooks searchBooks)
        {
            foreach(Book b in db)
            {
                if(b.softCover)
                {
                    searchBooks(b);
                }
            }
        }
    }

    public class Total
    {
        public decimal total;
        public void CalculateTotalPrice(Book book)
        {
            total += book.price;
        }
    }

    public delegate void SearchBooks(Book book);

    public class Book
    {
        public string title;
        public string owner;
        public decimal price;
        public bool softCover;

        public Book(string title, string owner, decimal price, bool softCover)
        {
            this.title = title;
            this.owner = owner;
            this.price = price;
            this.softCover = softCover;
        }
    }