php - 是否有静态调用对象方法的设计模式

标签 php algorithm design-patterns static

基本上,我正在尝试创建一个用于处理文件和目录的库。

这个想法是为 FileFindingFileReadingFileWriting 等提供单独的类。

我试图搜索是否有任何设计模式可以实现类似的目标:

可以说只有一次类(class)

<?php namespace vendor/FileHandler;

 class FileHandler {}

现在在图书馆里我有特定的类(class)

<?php namespace vendor/FileHandler;

class FileFinder 
{
     /**
     * Find files by their types
     * 
     * @param string $path path to find files in.
     * @param mixed $type string or array of file type/types (extensions).
     * @return array array of file names.
     */
    public function findFilesByType($path, $type)
    {
        // do logic here.
        return $files;
    }
}

现在我希望我的库用户使用主类 FileHandler::findFilesByType(); 调用 FileFinder::findFilesByType()

请注意:FileFinder::findFilesByType() 不是静态方法,但我希望将其用作 类 FileHanlder

的静态方法

更新: 我上面问的问题似乎与 Laravel 的 Facade 模式类似。但他们的实现超出了我的想象。即使我不确定 Facade 模式是否可以做到这一点。

最佳答案

外观应该保留每个类的静态实例,这些类提供您自己想要转发给库用户的功能。

在外观的静态方法中,利用上述对象并将方法调用转发给它们。 仅当您转发的对象是无状态的时才使用此方法, 否则,您必须在 Facades 方法内创建适当的对象,以便不在方法调用之间传播状态信息。

下面是一个用 java 编写的小例子,但你会明白的

public class Facade {
    private static final HashComputer computer = new HashComputer();

    // since this operation changes state of accumulator,
    // it has to create one on each invocation
    public static List<String> accumulate(String... args) {
        Accumulator acc = new Accumulator();
        for (String arg : args)
            acc.add(arg);

        return acc.collect();
    }

    // this operation does not change state of the object it delegates to,
    // so there is no need to create a new instance on every invocation
    public static int computeHash(String s) {
        return computer.hashFor(s);
    }

    // has stateless instances
    private static class HashComputer {
        public int hashFor(String s) {
            return s.hashCode();
        }
    }

    // instances have state depending on state of list
    private static class Accumulator {
        List<String> arguments = new ArrayList<String>();
        public void add(String s) {
            arguments.add(s);
        }
        public List<String> collect() {
            return Collections.unmodifiableList(arguments);
        }
    }
}

严格来说,这种实现外观的确切方法正好适合您的需求。外观不一定是具有静态方法的实用程序类,它也可以是类的实例。

外观设计模式背后的原则是从一组类(或整个层)的内在函数中抽象出来,这些类负责一些通用功能,封装操作并授予对它们的简单(也许是高级)访问.


正如 @PeeHaa 在他的评论中提到的,这种静态外观方法确实不是 OOP 意义上的,因为违反了 law of demeter ,其中表示:

Class的方法method应该只调用方法

  • 属于
  • 方法创建的对象
  • 关于方法的参数
  • Class的实例变量上

从这个意义上讲,您不使用带有静态方法的外观,因为您调用的是类上的方法,而不是类的实例上的方法。

关于php - 是否有静态调用对象方法的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29429926/

相关文章:

php - SQL AVG 函数不考虑空单元格

防盗链PHP代码

c# - 3 层架构和下拉列表等小细节

c# - 如何简化具有许多属性的viewmodel/model的使用?

c# - WCF 服务 : Asynchronous method or BackgroundWorker

php - 在线编辑后阿拉伯字体显示为问号

php - PHP中用图案图像填充图像的透明部分

algorithm - 如何找到矢量路径的方向

algorithm - RMQ使用两个fenwick树(二叉索引树)

java - 两个数之和等于给定数