PHP 패턴
PHP/매뉴얼 번역 2008/06/20 00:40패턴은 가장좋은 방법과 좋은 설계를 기술하기위한 수단이다. 패턴은 일반적인 프로그램상의 과제에 유연한 해결책을 제공한다.
Factory
Factory 패턴으로 실행시에 오브젝트를 초기화할 수 있다. 오브젝트를 "제조한다"는 면에서 닮았기에 Factory 패턴이라는 이름이 붙었다. 패러미터화된 Factory 가 생성하는 클래스명을 패러미터로 받는다.
패러미터화된 팩토리 메소드의 예
class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Driver not found');
}
}
}
?>
위 메소드를 클래스내에서 정의함으로 해서 실행시에 로드되는 드라이버를 생성할 수 있게 된다. Example 클래스가 데이터베이스 추상화클래스에서 MySQL 및 SQLite 드라이버를 로드하면 다음과 같이 할 수 있다.
// Load a MySQL Driver
$mysql = Example::factory('MySQL');
// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?>
Singleton
Singleton 패턴은 클래스의 인스턴스가 하나만 필요한 경우에 적용된다. 가장 일반적인 예가 데이터베이스에의 접속이다. 이 패턴을 구현하게 되면 프로그래머는 이 단일 인스턴스가 다른 많은 오브젝트로부터 쉽게 억세스할 수 있도록 할 수 있다.
class Example
{
// Hold an instance of the class
private static $instance;
// A private constructor; prevents direct creation of object
private function __construct()
{
echo 'I am constructed';
}
// The singleton method
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Example method
public function bark()
{
echo 'Woof!';
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?>
// This would fail because the constructor is private
$test = new Example;
// This will always retrieve a single instance of the class
$test = Example::singleton();
$test->bark();
// This will issue an E_USER_ERROR.
$test_clone = clone $test;
?>
원문링크 : http://www.php.net/manual/en/language.oop5.patterns.php
목차에
PHP 클래스와 오브젝트 ( Classes and Objects ) PHP 5
'PHP > 매뉴얼 번역' 카테고리의 다른 글
| PHP 타이프 힌팅 (0) | 2008/06/20 |
|---|---|
| PHP 오브젝트의 비교 (0) | 2008/06/20 |
| PHP 오브젝트의 클론 생성 (0) | 2008/06/20 |
| PHP final 키워드 (0) | 2008/06/20 |
| PHP 매직메소스 (0) | 2008/06/20 |
| PHP 패턴 (0) | 2008/06/20 |
| PHP 오브젝트 이터레이션 (0) | 2008/06/20 |
| PHP 오버로드 (0) | 2008/06/20 |
| PHP 오브젝트 인터페이스 (0) | 2008/06/20 |
| PHP 클래스의 추상화 (0) | 2008/06/19 |
| PHP 클래스 정수 (0) | 2008/06/19 |