vendredi 29 mars 2019

Which design pattern solve the multiple rules checking?

I want to save some files of an article which are posted to an ASP.NET MVC Core action. Then i have them as IFormFile in HttpContext. These files can be image, video, and document. Each of these file have their restrictions to save such as size or extension and each type can have own specific restriction. For example the main image of article should not large that 1500* 900. So I decide to put this design to them:

Class Diagram

And my codes:

public interface IArticleFile
{
    void CheckFileRules(IFormFile formFile);
    void SaveFile(IFormFile formFile, string path);
}

public interface IArticleImage : IArticleFile
{
    void CheckImageRules(IFormFile formFile);
}

public interface IArticleVideo : IArticleFile
{
    void CheckVideoRules(IFormFile formFile);
}

public class ArticleMainImage: IArticleImage
{
    public void CheckFileRules(IFormFile formFile) {/*CHECK STH*/}
    public void CheckImageRules(IFormFile formFile) {/*CHECK STH*/}
    public void SaveFile(IFormFile formFile, string path) { /* Save file */ }
}
public class ArticleSummaryImage : IArticleImage
{
    public void CheckFileRules(IFormFile formFile) {/*CHECK STH*/}
    public void CheckImageRules(IFormFile formFile) {/*CHECK STH*/}
    public void SaveFile(IFormFile formFile, string path) { /* Save file */ }
}

public class ArticleDto
{
    /*some properties*/
    public IFormFile MainImage { get; set; }
    public IFormFile SummaryImage { get; set; }
    public IFormFile ThumbnailImage { get; set; }
    public List<IFormFile> Videos { get; set; }
    public List<IFormFile> Documents { get; set; }

}

public class Article: IArticleService
{
    public void AddArticle(ArticleDto articleDto)
    {
        var articleMainImage = new ArticleMainImage();
        articleMainImage.CheckFileRules(articleDto.MainImage);
        articleMainImage.CheckImageRules(articleDto.MainImage);

        var articleSummaryImage = new ArticleMainImage();
        articleSummaryImage.CheckFileRules(articleDto.MainImage);
        articleSummaryImage.CheckImageRules(articleDto.MainImage);

        //Do these for Thumbnail image, videos, and documents
    }
}

But, I think I should use a design pattern here to make them easy to manipulate later and avoid from repeating some of my codes in Service layer. How can I do this in better way?

Aucun commentaire:

Enregistrer un commentaire