I had phases of this with our son. I found that it took a while to go away, so I'm not sure if my method of dealing with it had much to do with it or whether it was more the passage of time.
Don't treat him in a way you want him to copy. In my case, I don't shout or loose my temper/cool. A firm raised voice that makes it clear I am completely in control of myself and of the situation (i.e. him) is a good start.
When he's in "good" mode, make sure he is well rewarded with affection and, if appropriate permission to do things that might otherwise be off limits or just treats.
When he's in bad mode, explain in clear simple and short phrases what he's doing wrong and, if he will listen, why its wrong. At that point, make it clear he is still loved and offer a way to get back to being "good".
Resist the temptation to make threats you don't follow through on. If you say "No TV for a week" then you must follow through!
Most of all clear consistent and simple rules with unchanging outcomes, calmly implemented.