Here is what I am trying to implement in my program:
- The program should open a zip file containing many data files
- The format of the data files may vary between zip files (for example, csv, with tab delimiters, or it may even be some kind of binary file that requires decoding)
- However, in the zip file all data files will be of the same type
I read "Design Patterns" by Gamma et al. And reviewed the Abstract Factory pattern to try to solve this problem.
Ideally, I want to have one class for a Zip file that can read any type of data file inside it. I think I would have two classes - FileTypeA and FileTypeB, which could handle different data formats (although there may be more in the future). I would like to talk about my ZipFile class, what type of file to use when reading data.
So far this is what I came up with:
<?php
abstract class DataFileFactory{
abstract function createFile($id);
}
class FileAFactory extends DataFileFactory{
public function createFile($id){
$file = new FileA();
$file->setSampleId($id);
return $file;
}
}
class FileBFactory extends DataFileFactory{
public function createFile($id){
$file = new FileB();
$file->setSampleId($id);
return $file;
}
}
abstract class DataFile{
abstract function readData();
abstract function setSampleId();
}
class FileA extends DataFile{
public function readData(){
echo "Reading data from a file A<br/>";
}
public function setSampleId(){
echo "Setting sample id of a file A<br/>";
}
}
class FileB extends DataFile{
public function readData(){
echo "Reading data from a file B<br/>";
}
public function setSampleId(){
echo "Setting sample id of a file B<br/>";
}
}
class ZipFile{
private $files = array("file1.txt","file2.txt","file3.txt","file4.txt");
private $sampleId = 1;
public function readFiles(DataFileFactory $factory){
foreach($this->files as $fileName){
$file = $factory->createFile($this->sampleId);
$file->readData();
echo "object created of type: ".get_class($file)."<hr/>";
}
}
}
$zip = new ZipFile();
$factory = new FileAFactory();
$zip->readFiles($factory);
Can someone tell me: (A) Is this a good way to achieve what I'm looking for, or is there some simpler way to do this? (B) Is this actually an abstract Factory pattern, or am I completely misunderstood?
Thanks in advance!
source
share