Monday, 4 February 2019

Using Builder pattern in C#


Builder Pattern Sample in C#

Builder pattern – ob’ektlarni qadamba-qadam yaratishga mo’ljallangan patterndir.

Masalan har bir kitobning Id, Name, Author nomli xususiyatlari uchun BookBuilder qanday realizatsiya qilinishini ko’ramiz
public sealed class Book
    {
        private readonly int id;
        private readonly string name;
        private readonly string author;
        public Book(int id, string name,string author)
        {
            this.id = id;
            this.name = name;
            this.author = author;
        }
        public string GetInfo()
        {
            return $"Book INFO: id:{id}, name: {name}, author:{author}";
        }
    }

Endi BookBuilder classini realizatsiya qilamiz:

public sealed class BookBuilder : IBookBuilderSetId, IBookBuilderSetName, IBookBuilderSetAuthor, IBookBuilder
    {
        private int id;
        private string name;
        private string author;
        private BookBuilder() { }
        public static IBookBuilderSetId CreateNew()
        {
            return new BookBuilder();
        }

       

        public IBookBuilderSetName SetId(int id)
        {
            this.id = id;
            return this;
        }


        public IBookBuilderSetAuthor SetName(string name)
        {
            this.name = name;
            return this;
        }

        public IBookBuilder SetAuthor(string author)
        {
            this.author = author;
            return this;
        }

        public Book Build()
        {
            return new Book(id, name, author);
        }
    }



    public interface IBookBuilderSetId
    {
        IBookBuilderSetName SetId(int id);
    }

    public interface IBookBuilderSetName
    {
        IBookBuilderSetAuthor SetName(string name);
    }

    public interface IBookBuilderSetAuthor
    {
        IBookBuilder SetAuthor(string author);
    }

    public interface IBookBuilder
    {
        Book Build();
    }


Ishlatilishi:

static void Main(string[] args)
{
    Book myBook = BookBuilder.CreateNew()
    .SetId(10)
    .SetName("Learning .Net Core")
    .SetAuthor("Mike Tyson")
    .Build();
    System.Console.WriteLine(myBook.GetInfo());
    System.Console.ReadLine();
}

Natijasi:
Book INFO: id:10, name: Learning .Net Core, author: Mike Tyson



No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Tasks and Threads

  Differences Between Task And Thread: 1. The Thread class is used for creating and manipulating a thread in Windows.  2. A Task represents ...