开发者

Design pattern for reducing code duplication in different types of collections of the same object

开发者 https://www.devze.com 2023-04-05 08:21 出处:网络
Let\'s assume I have a class which defines an image object. The image can belong to an album, and the album can belong to a folder. This data is stored in MySQL. The data is also cached. In the cache,

Let's assume I have a class which defines an image object. The image can belong to an album, and the album can belong to a folder. This data is stored in MySQL. The data is also cached. In the cache, it is stored in a denormalized form i.e. folders keep track of images they are associated with, and so do albums. This is implemented for performance reasons.

Whenever a photo is created now, it is added 开发者_如何学Cto both the folder and the album in the cache. Because the code is the same for adding the photos to the cache, and only the cache keys change, a separate object is made called CachedImageSet. The folder and the album instantiate CachedImageSet with their unique id and the type of collection, and they call CachedImageSet to add and remove images and to get a list of images in the set.

I don't want client code to directly interact with CachedImageSet, so I have methods in the folder and album classes that are wrappers for the methods of CachedImageSet. This results in a lot of code duplication. Is there any design pattern that would help me get rid of this duplication? I'm using PHP, MySQL, and Redis (for the cache-layer).


I may be way off base, but if I interpreted your question correctly, I would use the factory pattern.

Something like this (which is simplified of course):

<?php

abstract class Folder {

    public static function factory($driver = 'Database')
    {
        $class = 'Folder_'.str_replace('/', '_', $driver);

        return new $class();
    }

}

class Folder_Database {

    public function get() {
        // Fetch folder from database
    }

    public function save() {
        // Save folder to database
    }

}

class Folder_Cache {

    public function get() {
        // Fetch folder from Redis
    }

    public function save() {
        // Save folder to Redis
    }

}

// Usage:
$folder = Folder::factory('Cache');
$folder->save('....');


MVC is a very good design pattern in my opinion, but i think you should chose the one that suits you most, suit your self in wikipedia (Design Patterns)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号