在一个中使用两个类:设计错误?

时间:2011-01-02 23:07:27

标签: php design-patterns

我写了这两个简单的加密和解密字符串的类:

Encode.php

    class Encode {
        protected funcion do_encode($string) { .. }
    }


Decode.php

    class Decode {
        protected funcion do_decode($string) { .. }
    }

喜欢做的是:

Encrypt.php

    class Encrypt extends Encode, Decode {
        protected $stuff_for_parents;

        function __construct($configs) {
            $this->stuff_for_parents = $configs['SomeConf'];
        }

        public function encode($string) { $this->do_encode($string); }
        public function decode($string) { $this->do_decode($string); }
    }

但是我们不能包含多个类,所以:失败。
现在我的问题是:

  1. 这是一个设计问题吗?因为这种情况对我来说并不奇怪,是吗?
  2. 是否有另一种方法可以让一个对象同时使用不同类中的函数?排序$encrypt->encode($str); $encrypt->decode($str);

4 个答案:

答案 0 :(得分:5)

如果您希望Encode和Decode成为单独的类,则可以在Encrypt中创建它们的实例。例如:

<?
class Encrypt {
  private $encoder;
  private $decoder;
  public function __construct() {
    $this->encoder = new Encode();
    $this->decoder = new Decode();
  }
  public function encode($string) {
    return $this->encoder->encode($string);
  }
  public function decode($string) {
    return $this->decoder->decode($string);
  }
}
?>

在该示例中,Encode和Decode必须是具体类。但您可能需要考虑使用接口。如果您认为在不同情况下可能需要使用不同类型的Encode和Decode对象,则接口非常有用。例如,您可能拥有TripleDESEncode类和BlowfishEncode类。它们都可以实现一个通用接口,如下所示:

<?
interface IEncode {
  public function encode($string);
}
class TripleDESEncode implements IEncode {
  public function encode($string) {...}
}
class BlowfishEncode implements IEncode {
  public function encode($string) {...}
}
?>

在这种情况下,您可能希望先创建要使用的特定实例,然后将它们传递给Encrypt的构造函数。这称为依赖注入:

<?
class Encrypt {
  public function __construct(IEncode $encoder, IDecode $decoder) {
    $this->encoder = $encoder;
    $this->decoder = $decoder;
  }
  ...
}

$myEncrypt = new Encrypt(new BlowfishEncode(), new BlowfishDecode());
echo $myEncrypt->encode('test');
?>

答案 1 :(得分:2)

将算法封装在单独的类中没有任何问题(事实上,如果您希望灵活地更改这些算法,特别是在运行时,这是一个好习惯),但是,您可能需要的是组合而不是继承:

class Encrypt {
    private $encoder;
    private $decoder;
    protected $stuff_for_parents;

    function __construct($configs, $encoder, $decoder) {
        $this->stuff_for_parents = $configs['SomeConf'];
        $this->encoder = $encoder;
        $this->decoder = $decoder;
    }

    public function encode($string) { $this->encoder->do_encode($string); }
    public function decode($string) { $this->decoder->do_decode($string); }
}

答案 2 :(得分:0)

我认为你应该在Encryption类中创建两个方法/函数。这是非常合乎逻辑的。

它确实有意义,但它可以通过编程语言允许的方式完成。编码解码是加密类应该执行的不同功能,因此这些应该是方法。

答案 3 :(得分:0)

我会写的是:

class Encrypt
{
    protected $stuff_for_parents;

    function __construct($configs) {
        $this->stuff_for_parents = $configs['SomeConf'];
    }

    protected funcion encode($string)
    {
    }

    protected funcion decode($string)
    {
    }
}