Answer the question
In order to leave comments, you need to log in
How to solve this nicely with OOP?
Rebzi, tell me how to solve this beautifully, from the point of view of OOP.
The source class is given, in which there are 2 methods: save, delete.
There are 2-N "types" of materials that this class can work with. With each material, you can carry out all these actions, but with each you need to do it differently. If you approach the task from the point of view: this is how it will work, then you can do it like this:
public function save($one,$type){
if($type == 'type_1'){
//some actions
}elseif($type == 'type_2'){
//else actions
}
}
..
Answer the question
In order to leave comments, you need to log in
probably in your case you need a design pattern Factory method.
class MaterialFactory
{
public static function build($type)
{
// тут генерим путь до класса на основе его типа
return new $className();
}
}
class Material
{
public function save()
{
// тут свои действия
}
}
class SuperMaterial
{
public function save()
{
// тут другие действия
}
}
public function save($one,$type){
$obj = MaterialFactory::build($type);
$obj->save();
}
The code is in Java, but the essence of OOP is the same. The material is the interface, the concrete material is its implementation. We feed the interface into the methods of the first class, then polymorphism works.
class A {
void save(Material m) {
m.save();
}
void delete(Material m) {
m.delete();
}
}
interface Material {
void save();
void delete();
}
class MaterialNumberOne implements Material {
void save() {
//делаем что нужно для первого материала
}
void delete() {
//делаем что нужно для первого материала
}
}
class MaterialNumberTwo implements Material {
void save() {
//делаем что нужно для второго материала
}
void delete() {
//делаем что нужно для второго материала
}
}
// юзаем так
public static void main(String[] args) {
Material m1 = new MaterialNumberOne();
Material m2 = new MaterialNumberTwo();
A a = new A();
a.save(m1);
a.delete(m1);
a.save(m2);
a.delete(m2);
}
interface StorableMaterial
{
public function save();
}
class Material implements StorableMaterial
{
public function save()
{
// ...
}
}
class SuperMaterial implements StorableMaterial
{
public function save()
{
// ...
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question